MongoDB简单使用 —— 驱动

时间:2023-03-08 15:48:24

C#中可以通过官方的驱动MongoDB.Drvier来使用,使用Nuget安装即可。

Install-Package MongoDB.Driver

Bson文档操作:

using MongoDB.Bson;
using MongoDB.Driver;
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<BsonDocument>("bar"); await collection.InsertOneAsync(new BsonDocument()
{
["Id"] = "",
["Name"] = "Jack",
["Age"] = ,
}
); var list = await collection.Find(new BsonDocument("Name", "Jack"))
.ToListAsync(); foreach(var document in list)
{
Console.WriteLine(document["Name"]);
}

强类型对象:

强类型对象也是支持的,并且支持Linq查询

using MongoDB.Bson;
using MongoDB.Driver;
public class Person
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<Person>("bar"); await collection.InsertOneAsync(new Person { Name = "Jack" }); var list = await collection.Find(x => x.Name == "Jack")
.ToListAsync(); foreach(var person in list)
{
Console.WriteLine(person.Name);
}

对于强类型对象,需要有一个名为Id的字段,不一定要求是ObjectId类型。并且支持Linq查询。

更多示例,可以查看官方文档