欢迎投稿

今日深度:

野心勃勃的NoSQL新贵 MongoDB应用实战(1)(6)

四、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、代码解析

下面以一个插入的操作为例,来一步一步解释代码:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. //添加命名空间  
  6. using MongoDB.Bson;  
  7. using MongoDB.Driver;  
  8. namespace ConsoleApplication3  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             //MongoDB服务器连接串  
  15.             string connectionString = "mongodb://192.168.1.103";  
  16.             MongoServer server = MongoServer.Create(connectionString);  
  17.             //连接到 mongodb_c_demo 数据库  
  18.             MongoDatabase db = server.GetDatabase("mongodb_c_demo");  
  19.             //获取集合 fruit  
  20.             MongoCollection collection = db.GetCollection("fruit");  
  21.             //创建对象 fruit_1  
  22.             BsonDocument fruit_1 = new BsonDocument  
  23.             {  
  24.               { "name""apple" },  
  25.               { "color""red" }  
  26.             };  
  27.             //创建对象 fruit_2  
  28.             BsonDocument fruit_2 = new BsonDocument  
  29.             {  
  30.               { "name""banana" },  
  31.               { "color""yellow" }  
  32.             };  
  33.             //将对象 fruit_1 放到集合 fruit 中  
  34.             collection.Insert(fruit_1);  
  35.             //将对象 fruit_2 放到集合 fruit 中  
  36.             collection.Insert(fruit_2);  
  37.             //以上代码完成的就是向fruit表中插入2条数据,用mysql的语法解释即  
  38.             //insert into mongodb_c_demo.fruit (name, color)   
  39.             //values ('apple', 'red'), ('banana', 'yellow');  
  40.         }  
  41.     }  

4、通过MongoDB Shell来验证是否插入:

  1. > use mongodb_c_demo  
  2. switched to db mongodb_c_demo  
  3. > db.fruit.find();   
  4. "_id" : ObjectId("4da1c5fdfad96211a08f5752"), "name" : "apple""color" : "red" }  
  5. "_id" : ObjectId("4da1c5fdfad96211a08f5753"), "name" : "banana""color" : "yellow" }  
  6. >  


www.htsjk.Com true http://www.htsjk.com/shujukujc/18864.html NewsArticle 四、MongoDB客户端访问 C# 接下来我们要开始最简单的MongoDB连接,访问数据之旅了。MongoDB提供各种主流与非主流语言的开发驱动,以便适应各个方向的开发...
评论暂时关闭