使用MongoDB和ASP.NET MVC进行分页的有效方法 [英] Efficient way of paging with MongoDB and ASP.NET MVC

查看:220
本文介绍了使用MongoDB和ASP.NET MVC进行分页的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在创建一个应用程序MongoDB作为数据库,并且正在使用用于MongoDB的官方C#驱动程序.我们有一个包含数千条记录的集合,我们想创建带有分页的列表.我已经阅读了文档,但是没有使用MongoDB C#官方驱动程序进行分页的有效方法.

We are creating an application MongoDB as database and we are using official C# driver for MongoDB. We have one collection which contains thousands of records and we want to create list with paging. I have gone through documentation but there is not efficient way of paging with MongoDB C# official driver.

我的要求是仅从数据库中准确获取50条记录.我已经看到了很多示例,但是它们都通过LINQ进行了所有收集并执行了跳过和获取操作,在我们的案例中这是行不通的,因为我们不想获取内存中的数千条记录.

My requirement is to exactly fetch only 50 records from database. I have seen many examples but that get all collection and perform skip and take via LINQ which is not going to work in our case as we don't want to fetch thousand of records in memory.

请提供任何示例代码或链接.任何帮助将不胜感激.

Please provide any example code or link for that. Any help will be appreciated.

预先感谢您的帮助.

推荐答案

您可以使用

You can use SetLimit on the cursor that represents the query. That will limit the results from MongoDB, not only in memory:

var cursor = collection.FindAll(); // Or any other query.
cursor.SetLimit(50); // Will only return 50.
foreach (var item in cursor)
{
    // Process item.
}

您还可以使用 SetSkip 设置跳过(令人惊讶):

You can also use SetSkip to set a skip (surprisingly):

cursor.SetSkip(10);

注意:在枚举光标之前,必须在光标上设置这些属性.设置这些设置将无效.

Note: You must set those properties on the cursor before enumerating it. Setting those after will have no effect.

顺便说一句,即使您仅使用LinqSkipTake,您也不会检索成千上万的文档. MongoDB 自动按大小分批处理结果(第一个批处理大约是1mb,其余各为4mb),因此您只会获得第一批并从其中取出前50个文档.

By the way, even if you do only use Linq's Skip and Take you won't be retrieving thousands of documents. MongoDB automatically batches the result by size (first batch is about 1mb, the rest are 4mb each) so you would only get the first batch and take the first 50 docs out of it. More on

我认为这里的LINQ有点混乱:

I think there's some confusion about LINQ here:

通过LINQ获取所有收集并执行跳过和获取操作,因为我们不想在内存中获取数千条记录,因此在我们的案例中不起作用.

that get all collection and perform skip and take via LINQ which is not going to work in our case as we don't want to fetch thousand of records in memory.

SkipTakeIEnumerable IQueryable上的扩展方法. IEnumerable用于内存集合,IQueryable操作是

Skip and Take are extension methods on both IEnumerable and IQueryable. IEnumerable is meant for in memory collections, but IQueryable operations are translated by the specific provider (the C# driver in this case). So the above code is equivalent with:

foreach (var item in collection.AsQueryable().SetLimit(50))
{
    // Process item.
}

这篇关于使用MongoDB和ASP.NET MVC进行分页的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆