Find 和 FindAsync 之间的区别

Difference between Find and FindAsync(Find 和 FindAsync 之间的区别)
本文介绍了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 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to do a full outer join in Linq?(如何在 Linq 中进行完整的外部联接?)
How do I group data in an ASP.NET MVC View?(如何在 ASP.NET MVC 视图中对数据进行分组?)
how to update the multiple rows at a time using linq to sql?(如何使用 linq to sql 一次更新多行?)
how to recognize similar words with difference in spelling(如何识别拼写不同的相似词)
C# Linq to SQL: How to express quot;CONVERT([...] AS INT)quot;?(C# Linq to SQL:如何表达“CONVERT([...] AS INT)?)
Why do quot;linq to sqlquot; queries starts with the FROM keyword unlike regular SQL queries?(为什么要“linq to sql与常规 SQL 查询不同,查询以 FROM 关键字开头?)