-- MongoDb.Driver .net版驱动基本用法(Find,Projection,FindOptions,FilterDefinition,Sort,泛型,Bson,BsonDocument等)
【官网】:https://docs.mongodb.com/drivers/csharp/
应用场景
有时当我们想用c# .net版的MongoDb驱动时,需要了解其基本用法。基础资源
MongoDB.Bson.dll,MongoDB.Driver.dll
使用须知
官方的MongoDB.NET驱动程序提供与MongoDB的异步交互。驱动驱动程序是一个核心库和一个BSON库。 Driver: 与MongoDB对话的完全异步驱动程序。 GridFS:基于MongoDB构建的分布式文件系统。 Core Driver:MongoDB驱动程序构建在一个新的核心库之上,任何人都可以使用它来构建替代的或实验性的高级API。 BSON Library:一个独立的BSON库,具有可用于构建高性能序列化程序的序列化基础结构。
配置步骤
无
常见问题
快速入门
A)客户端连接到服务端。
// 或者使用string连接本地服务器,localhost=127.0.0.1,连接到单实例var client = new MongoClient("mongodb://config.net.cn:27017");
// 连接到复制集(多节点)
var client = new MongoClient("mongodb://config.net.cn:27017,config.net.cn:27018,config.net.cn:27019");
// 支持订阅,更多特性的连接方式。
var credentials = MongoCredential.CreateCredential(
databaseName: "BookAds",username: "账号",password: "密码"
);
var mongoClient = new MongoClient(new MongoClientSettings()
{
Server = new MongoServerAddress("mongodb://config.net.cn", 27022),
Credential = credentials,
ConnectionMode = ConnectionMode.Standalone,
ServerSelectionTimeout = TimeSpan.FromSeconds(15),
ClusterConfigurator = builder =>
{
builder.Subscribe(new SingleEventSubscriber<CommandStartedEvent>(CmdStartHandlerForFindCommand));//开始执行时的回调
builder.Subscribe(new SingleEventSubscriber<CommandSucceededEvent>(CmdSuccessHandlerForFindCommand));//执行成功后的回调
}
});
B)获取一个Database.
var _database = mongoClient.GetDatabase("BookAds");注: _database 保留了对BookAds集合的引用。
C)获取一个Collection。
c1)泛型模式。
var collection=_database?.GetCollection<BookAdsEntity>("BookAds");
c2)BsonDocument模式。
var collection = database.GetCollection<BsonDocument>("BookAds");
D)基本的Find(查询)命令。
d1)泛型模式.
var filterBuilder=new FilterDefinitionBuilder<LoginLog>();var filters=new List<FilterDefinition<LoginLog>>();
filters.Add(filterBuilder.In(t=>t.LoginType,new short[]{100,101}));
filters.Add(filterBuilder.Eq(t=>t.UserId,userId));
var filter=filterBuilder.And(filters);
var projection=Builders<LoginLog>.Projection.Include("UserId").Include("LoginType").Include("LoginTime").Include("Log");
var findOptions=new FindOptions<LoginLog>(){
Projection=projection,
Sort=Builders<LoginLog>.Sort.Descending(x=>x.LoginTime),
Limit=5
};
var cussor=await MongoDbCtx.EventLog.FindAsync(filter,findOptions);
var resultLogs=await cussor?.ToListAsync();
d2)BsonDocument模式。
示例1)
var document = collection.Find(new BsonDocument()).FirstOrDefault();
var documents = collection.Find(new BsonDocument()).ToList();
示例2)
FilterDefinitionBuilder<BsonDocument> builder = new FilterDefinitionBuilder<BsonDocument>();
var define= builder.Lt("Age", 122);
var list = collection.Find<BsonDocument>(define).ToListAsync();
[注1]释放资源的写法。
using (var cursor = await collection.FindAsync<BsonDocument>(filter)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (var document in batch) { var movieName = document.GetElement("name").Value.ToString(); Console.WriteLine("Movie Name: {0}", movieName); count++; } } } }
[注2]Or的查询条件构建。 var filter = Builders<Movie>.Filter.Or(new[] { new ExpressionFilterDefinition<Movie>(x => x.Name == "The Godfather"), new ExpressionFilterDefinition<Movie>(x => x.Name == "The Seven Samurai") }); [注3]Projection的写法。 var projection = Builders<Movie>.Projection.Include(x => x.Name).Include(x => x.Year).Exclude(x => x.MovieId);
E)基本的Insert(添加)命令。
E1)泛型模式.
var data = new Orders()
{
OrderId = 1,
Date = DateTime.Now,
Name = "Irfan",
TotalAmount = 10.0m,
};
await collections.InsertOneAsync(data);//单个添加
await collections.InsertManyAsync(new List<Orders>(){data});//批量添加
E2)BsonDocument模式。
var document = new BsonDocument { { "name", "MongoDB" }, { "type", "Database" }, { "count", 1 }, { "info", new BsonDocument { { "x", 203 }, { "y", 102 } } } };collection.InsertOne(document);//同步
await collection.InsertOneAsycn(document);//异步
F)基本的Update(修改)命令。
f1)泛型模式。
var filterDefinitionBuilder = new FilterDefinitionBuilder<Student>();
var updateDefinitionBuilder = new UpdateDefinitionBuilder<Student>();
await studentsCollection.UpdateOneAsync(
filterDefinitionBuilder.Eq<string>((Student x) => x.Id, 1001),
updateDefinitionBuilder.Inc<int>((Student x) => x.Age, 1)
);
f2)BsonDocument模式。
var filter = Builders<BsonDocument>.Filter.Eq("i", 10);var update = Builders<BsonDocument>.Update.Set("i", 110);
collection.UpdateOne(filter, update); //同步
G)基本的delete(删除)命令。
g1)泛型模式。
var filterDefinitionBuilder = new FilterDefinitionBuilder<Student>();
var filter = filterDefinitionBuilder.Eq((Student x) => x.Id, 1001);
await studentsCollection.DeleteOneAsync(filter);
g2)BsonDocument模式。
var filter = Builders<BsonDocument>.Filter.Eq("i", 110));collection.DeleteOne(filter); //同步
await collection.DeleteOneAsync(filter); //异步
H)Aggregate(聚合)查询。
h1)泛型模式。
var aggregate = collection.Aggregate()
.Match(Builders<Movie>.Filter.Where(x => x.Name.Contains("Godfather")))
.Group(new BsonDocument
{
{"_id", "$year"},
{"count", new BsonDocument("$sum", 1)}
});
var results = aggregate.ToList();
h2)BsonDocument模式。
var data = collection.Aggregate().Group(new BsonDocument
{
{ "_id", "$year" },
{ "count", new BsonDocument("$sum", 1) }
});
foreach (var item in data.ToList())
{
Console.WriteLine("Item retrieved {0}", item.ToString());
}