MongoDB簡單使用 —— 基本操作
阿新 • • 發佈:2018-04-15
ons mongo code mongdb b- 方式 檢查 簡潔 2.4
本身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
- MongoDB 教程
- MongoDB with C#
MongoDB簡單使用 —— 基本操作