在C#中使用官方驱动操作MongoDB

MongoDB的官方驱动下载地址:https://github.com/mongodb/mongo-csharp-driver/releases

目前最新的版本是2.10,支持.NET 4.5以上。由于我现在的程序还在.NET4.0上面构建,所以这里使用1.10.1版本。

添加引用

解压下载到的驱动,然后在我们的程序中添加引用:

MongoDB.Bson.dll
MongoDB.Driver.dll

然后在代码中添加Using:

using MongoDB.Bson;
using MongoDB.Driver;

 

创建Client、Server、Database

var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var db = server.GetDatabase("mydb");

connectionString可以从配置文件中获取。

client对象是线程安全的,那么,我们可以把它存到一个全局的变量中。

有了db对象,我们就可以进行访问了。

使用Collection

Collection是文档(document)的集合,可以理解为我们的数据表。而每一个文档就是我们的一行数据。在MongoDB的驱动中,我们有两种方式来使用Collection:

  1. 使用 BsonDocument 模型
  2. 使用自定义的实体模型

如果我们的文档结构比较复杂,或者定义为实体模型比较困难,那么推荐使用BsonDocument模型。

如果我们的文档结构清晰,存储的字段也是固定的,那么推荐使用自定义的实体模型。实体对象的格式如下:

public class Entity
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

我们在获取Collection引用的时候,需要提供一个文档类型:

var collection = db.GetCollection<Entity>("entities");

CURD操作

在有了Collection之后,我们可以写一个CURD的例子:

var collection = db.GetCollection<Entity>("entities");

var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id;

var query = Query<Entity>.EQ(e => e.Id, id);
entity = collection.FindOne(query);

entity.Name = "Dick";
collection.Save(entity);

var update = Update<Entity>.Set(e => e.Name, "Harry");
collection.Update(query, update);

collection.Remove(query);

 

posted @ 2015-10-20 13:30  拓荒者FF  阅读(11589)  评论(2编辑  收藏  举报