obj*_*t88 23 c# mongodb mongodb-query mongodb-csharp-2.0
我正在编写一个非常非常简单的查询,它根据其唯一ID从集合中获取文档.经过一些frusteration(我是mongo和async/await编程模型的新手),我想出了这个:
IMongoCollection<TModel> collection = // ...
FindOptions<TModel> options = new FindOptions<TModel> { Limit = 1 };
IAsyncCursor<TModel> task = await collection.FindAsync(x => x.Id.Equals(id), options);
List<TModel> list = await task.ToListAsync();
TModel result = list.FirstOrDefault();
return result;
Run Code Online (Sandbox Code Playgroud)
它很棒!但我一直看到对"查找"方法的引用,我解决了这个问题:
IMongoCollection<TModel> collection = // ...
IFindFluent<TModel, TModel> findFluent = collection.Find(x => x.Id == id);
findFluent = findFluent.Limit(1);
TModel result = await findFluent.FirstOrDefaultAsync();
return result;
Run Code Online (Sandbox Code Playgroud)
事实证明,这也很有效,太棒了!
我确信有一些重要的原因,我们有两种不同的方法来实现这些结果.这些方法有什么区别,为什么我要选择其中一种呢?
rno*_*nko 29
区别在于语法.
Find并且FindAsync两者都允许仅以相同的性能构建异步查询
FindAsync返回一次不加载所有文档的游标,并提供从DB游标逐个检索文档的界面.当查询结果很大时,它很有用.
Find通过方法为您提供更简单的语法,ToListAsync其中inside从文件中检索文档并一次返回所有文档.