Efficient way of paging with MongoDB and ASP.NET MVC

自闭症网瘾萝莉.ら 提交于 2020-01-02 10:12:50

问题


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.

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.

Thanks in advance for help.


回答1:


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.
}

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.


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


Edit: I think there's some confusion about LINQ here:

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.

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.
}


来源:https://stackoverflow.com/questions/24262020/efficient-way-of-paging-with-mongodb-and-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!