当前位置:Gxlcms > 数据库问题 > .NET Core也可以使用MongoDB了

.NET Core也可以使用MongoDB了

时间:2021-07-01 10:21:17 帮助过:2人阅读

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("Name", "Jack"));

var list = await collection.Find(new BsonDocument("Name", "Jack"))
    .ToListAsync();

foreach(var document in list)
{
    Console.WriteLine(document["Name"]);
}

或使用强类型方式:

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);
}

详细说明请参见官方文档:

http://mongodb.github.io/mongo-csharp-driver/

 

源代码:

https://github.com/zhongzf/mongo-csharp-driver

.NET Core也可以使用MongoDB了

标签:

人气教程排行