我正在编写一个非常非常简单的查询,它只是根据其唯一 ID 从集合中获取文档。经过一些挫折(我是 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;
成功了,太棒了!但我不断看到对“查找”方法的引用,我解决了这个问题:
IMongoCollection<TModel> collection = // ...
IFindFluent<TModel, TModel> findFluent = collection.Find(x => x.Id == id);
findFluent = findFluent.Limit(1);
TModel result = await findFluent.FirstOrDefaultAsync();
return result;
事实证明,这也行得通,太棒了!
我确信我们有两种不同的方法来实现这些结果是有一些重要原因的。这些方法之间有什么区别,为什么我应该选择其中一种?
最佳答案
区别在于语法。
Find
和 FindAsync
都允许构建具有相同性能的异步查询,只是
FindAsync
返回 cursor,它不会一次加载所有文档,并为您提供从数据库游标中逐个检索文档的界面。这在查询结果很大的情况下很有用。
Find
通过 ToListAsync
方法为您提供更简单的语法,它在其中从游标中检索文档并立即返回所有文档强>。
关于c# - Find 和 FindAsync 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46413550/