本身 MongoDB 直接支持的是 Bson 文档, Bson 文档在 C# 的官方驱动中对应的是 BsonDocument 类:
- var bsonDoc = new BsonDocument()
- {["_id"] = "123",
- ["Name"] = "Jack",
- ["Age"] = 32,
- };
由于 Bson 和 Json 本身非常类似, 所以它和 Json 一样, 和. net 对象之间互相转换是非常容易的.
- public class Person
- {
- public string Id { get; set; } = "123";
- public string Name { get; set; }
- public int Age { get; set; }
- }
- var person = BsonSerializer.Deserialize<Person>(bsonDoc);
- var doc = person.ToBsonDocument();
MongoDB 本身的增删改查都是直接针对 Bson 文档进行的:
- var collection = database.GetCollection<BsonDocument>("foo");
- collection.InsertOne(bsonDoc);
但为了使用方便, 也可以使用强类型的集合.
- var collection = database.GetCollection<Person>("foo");
- var person = new Person()
- {
- Id = "365",
- Name = "Jack",
- Age = 32,
- };
- // 插入
- collection.InsertOne(person);
- // 查询
- collection.Find(i => i.Name == "Jack");
- // 更新
- collection.ReplaceOne(i => i.Id == "365", person);
- // 删除
- collection.DeleteOne(i => i.Id == "365");
由于支持 Linq, 用起来还是非常方便的. 当然, 也可以使用 MongoDb 本身的查询功能.
- // 查询
- result = collection.Find(Builders<Person>.Filter.Eq(i=>i.Name, "Jack")).ToList();
- // 更新
- collection.ReplaceOne(Builders<Person>.Filter.Eq(i => i.Id, "365"), person);
- // 更新部分字段
- collection.UpdateOne(Builders<Person>.Filter.Eq(i => i.Id, "365"),
- Builders<Person>.Update.Set(i => i.Age, 30));
- // 删除
- collection.DeleteOne(Builders<Person>.Filter.Eq(i => i.Id, "365"));
甚至的, 如果也可以使用 MongDB 的命令, 也可以直接使用 Mongo 命令, 更加简洁.
- // 查询
- result = collection.Find("{ Name:'Jack'}").ToList();
- // 更新
- collection.UpdateOne("{Name:'Jack'}", "{$set:{'Age':'37'}}");
- // 删除
- collection.DeleteOne("{Name:'Jack'}");
这种方式类似 Sql, 非常简洁, 但是失去了类型检查, 至于如何使用, 则需要看具体场合了.
参考文档:
Definitions and Builders http://mongodb.github.io/mongo-csharp-driver/2.4/reference/driver/definitions/
MongoDB 教程 http://www.runoob.com/mongodb/mongodb-tutorial.html
MongoDB with C# http://www.fourthbottle.com/2016/08/or-in-mongodb-with-dotnet-driver.html
来源: http://www.bubuko.com/infodetail-2562791.html