超级神奇宝箱:【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(6) — MongoDB客户端访问 – C#
来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 18:58:30
四、MongoDB客户端访问 – C#
接下来我们要开始最简单的MongoDB连接,访问数据之旅了。MongoDB提供各种主流与非主流语言的开发驱动,以便适应各个方向的开发人员。
1、下载驱动
C#驱动的下载地址为:
https://github.com/downloads/mongodb/mongo-csharp-driver/CSharpDriver-1.0.0.4098.zip
将其解压到D:\mongodb\drivers\目录下,其中有2个重要的dll文件
MongoDB.Bson.dll --序列化、Json相关
MongoDB.Driver.dll --驱动
2、添加引用
新建一个C#的项目,添加引用,将上面两个dll文件引入到项目里面:
3、代码解析
下面以一个插入的操作为例,来一步一步解释代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- //添加命名空间
- using MongoDB.Bson;
- using MongoDB.Driver;
- namespace ConsoleApplication3
- {
- class Program
- {
- static void Main(string[] args)
- {
- //MongoDB服务器连接串
- string connectionString = "mongodb://192.168.1.103";
- MongoServer server = MongoServer.Create(connectionString);
- //连接到 mongodb_c_demo 数据库
- MongoDatabase db = server.GetDatabase("mongodb_c_demo");
- //获取集合 fruit
- MongoCollection collection = db.GetCollection("fruit");
- //创建对象 fruit_1
- BsonDocument fruit_1 = new BsonDocument
- {
- { "name", "apple" },
- { "color", "red" }
- };
- //创建对象 fruit_2
- BsonDocument fruit_2 = new BsonDocument
- {
- { "name", "banana" },
- { "color", "yellow" }
- };
- //将对象 fruit_1 放到集合 fruit 中
- collection.Insert(fruit_1);
- //将对象 fruit_2 放到集合 fruit 中
- collection.Insert(fruit_2);
- //以上代码完成的就是向fruit表中插入2条数据,用mysql的语法解释即
- //insert into mongodb_c_demo.fruit (name, color)
- //values ('apple', 'red'), ('banana', 'yellow');
- }
- }
- }
4、通过MongoDB Shell来验证是否插入:
- > use mongodb_c_demo
- switched to db mongodb_c_demo
- > db.fruit.find();
- { "_id" : ObjectId("4da1c5fdfad96211a08f5752"), "name" : "apple", "color" : "red" }
- { "_id" : ObjectId("4da1c5fdfad96211a08f5753"), "name" : "banana", "color" : "yellow" }
- >
【编辑推荐】
- 走进MongoDB的世界 展开MongoDB的学习之旅
- MongoDB学习笔记(一) MongoDB介绍及安装
- MongoDB学习笔记(二) 通过samus驱动实现基本数据操作
- MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
- MongoDB学习笔记(四) 用MongoDB的文档结构描述数据关系
【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(6) — MongoDB客户端访问 – C#
四、MongoDB客户端访问 – C#-野心勃勃的NoSQL新贵 MongoDB应用实战-...
【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(1)
【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(2) - MongoDB服务器安装
【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(3) — Windows版本服务器安装
【教程】野心勃勃的NoSQL新贵 MongoDB应用实战(4) — Linux版服务器安装
野心勃勃的NoSQL新贵 MongoDB应用实战(3)
MongoDB应用实战
mongodb有关的研究
MongoDB的应用:动态消息的设计实现
,通过 MongoDB 推动 NoSQL(第3部分)
基于MongoDB MapReduce的统计分析
MongoDB 优化
NoSQL就业形势分析:Cassandra和MongoDB最受欢迎 - CSDN 云计算频...
MongoDB学习——数据库管理命令
Mongodb源码分析--Mongos
Mongodb Mapreduce 初窥
Mongodb Mapreduce 初窥
我为什么选择MongoDB
MongoDB分片杂谈
MongoDB auto shard介绍
Memcache and Mongodb
MongoDB系列文章推荐
MongoDB: 10. MapReduce