Find 和 FindAsync 之间的区别

时间:2023-01-05
本文介绍了Find 和 FindAsync 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在编写一个非常非常简单的查询,它只是根据集合的唯一 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?

推荐答案

区别在于语法.FindFindAsync 都允许构建具有相同性能的异步查询,只是

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.

这篇关于Find 和 FindAsync 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!