Find 和 FindAsync 之间的区别
- 作者: -老衲要射了
- 来源: 51数据库
- 2022-10-28
问题描述
我正在编写一个非常非常简单的查询,它只是根据集合的唯一 ID 从集合中获取一个文档.经过一些挫折(我是 mongo 和 async/await 编程模型的新手),我想通了:
I am writing a very, very simple query which just gets a document from a collection according to its unique Id. After some frusteration (I am new to mongo and the async / await programming model), I figured this out:
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;
它有效,太棒了!但我一直看到对查找"方法的引用,我解决了这个问题:
It works, great! But I keep seeing references to a "Find" method, and I worked this out:
IMongoCollection<TModel> collection = // ... IFindFluent<TModel, TModel> findFluent = collection.Find(x => x.Id == id); findFluent = findFluent.Limit(1); TModel result = await findFluent.FirstOrDefaultAsync(); return result;
事实证明,这也有效,太棒了!
As it turns out, this too works, great!
我确信我们有两种不同的方式来实现这些结果是有一些重要原因的.这些方法之间有什么区别,为什么我应该选择其中一种?
I'm sure that there's some important reason that we have two different ways to achieve these results. What is the difference between these methodologies, and why should I choose one over the other?
推荐答案
区别在于语法.Find 和 FindAsync 都允许构建具有相同性能的异步查询,只是
The difference is in a syntax. Find and FindAsync both allows to build asynchronous query with the same performance, only
FindAsync 返回 cursor,它不会一次加载所有文档,并为您提供从 DB 游标中一一检索文档的界面.在查询结果很大的情况下很有帮助.
FindAsync returns cursor which doesn't load all documents at once and provides you interface to retrieve documents one by one from DB cursor. It's helpful in case when query result is huge.
Find 通过方法 ToListAsync 为您提供更简单的语法,其中它从游标中检索文档并一次返回所有文档强>.
Find provides you more simple syntax through method ToListAsync where it inside retrieves documents from cursor and returns all documents at once.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
