我正在编写一个非常非常简单的查询,它根据其唯一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)
事实证明,这也很有效,太棒了!
我确信有一些重要的原因,我们有两种不同的方法来实现这些结果.这些方法有什么区别,为什么我要选择其中一种呢?