简体   繁体   English

如何从MongoDB检索分页数据?

[英]How do I retrieve paged data from MongoDB?

I am building a C# ASP.net core web application which connects to MongoDB. 我正在构建一个连接到MongoDB的C#ASP.net核心Web应用程序。 My aim is to get data from MongoDB in form of pages, for example if I have 100 documents of a certain collection I would like to get 10 documents after ID=X and 10 documents before ID=X. 我的目标是以页面形式从MongoDB获取数据,例如,如果我有某个集合的100个文档,我想在ID = X之后获取10个文档,在ID = X之后获取10个文档。

What is the right syntax to get data like that knowing ID of a document (Previous 10 documents as well as Next 10 documents)? 什么是正确的语法来获取类似文档ID的数据(前10个文档以及后10个文档)?

You have to execute 2 queries: 您必须执行2个查询:

1) for the next 10 objects 1)接下来的10个对象

db.collection.find({_id:{$gt:object_id}}).limit(10)

2) for the previous 10 objects 2)对于前10个对象

db.collection.find({_id:{$lte:object_id}}).sort({_id:-1}).limit(10)

When you sort with _id, you will get the documents sorted (descending or ascending) by their creation timestamps. 当使用_id排序时,您将获得按其创建时间戳排序(降序或升序)的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM