一、安装MongoDB.Driver NuGet包
二、连接数据库
//创建MongoCredential对象
MongoCredential credential = MongoCredential.CreateCredential("testdb", "username", "password");
//创建MongoClientSettings,并添加身份验证信息
MongoClientSettings setting = new MongoClientSettings
{
Credential = credential,
Server = new MongoServerAddress("localhost", 27017)
};
Console.WriteLine("创建成功");
//连接到MongoDB
MongoClient client = new MongoClient(setting);
Console.WriteLine("连接成功");
三、连接到指定集合
var database = client.GetDatabase("testdb");
var collectionNames = database.ListCollectionNames().ToList();
bool select_collection_result = false;
foreach(var collectionName in collectionNames)
{
if(collectionName == "collection")
{
select_collection_result = true;
}
}
if(select_collection_result)
{
var collection = database.GetCollection<BsonDocument>("collection");
Console.WriteLine("连接到集合");
}
四、查询数据
查询最新的10条数据
List<BsonDocument> documents = collection.Find(new BsonDocument())
.Sort(new BsonDocument("_id", -1))
.Limit(10)
.ToList();
foreach (BsonDocument doc in documents)
{
Console.WriteLine(doc.GetValue("data").AsString);
}