简体   繁体   English

MongoDB REST API 动态数据分页

[英]MongoDB REST API dynamic data pagination

I am implementing REST API with Express and Mongoose.我正在使用 Express 和 Mongoose 实现 REST API。 I am stuck with a task to paginate results for a collection with large number of documents.我的任务是为包含大量文档的集合对结果进行分页。 Document is a social media post which has fields like: created_at , updated_at and score . Document 是一个社交媒体帖子,它具有以下字段: created_atupdated_atscore

Ordinary paging implementation using limit and page number doesn't work because the nature of data.由于数据的性质,使用限制和页码的普通分页实现不起作用。 Posts can be removed or added while user is browsing the results.当用户浏览结果时,可以删除或添加帖子。

I could implement range-based pagination as suggested in MongoDB documentation.我可以按照 MongoDB 文档中的建议实现基于范围的分页。 Last items in a page created_at value could be used to query next page.页面中的最后一项created_at值可用于查询下一页。

Post.find({ created_at: { $gt: req.query.next } })

But what if I want to sort results by score which is not unique or all scores are the same?但是,如果我想要的东西通过分数是不是唯一的或所有得分都是一样的结果进行排序?

There are multiple ways to do this, but in your case i would suggest to create the find / sort conditions dynamicly and use them in your find statement.有多种方法可以做到这一点,但在您的情况下,我建议动态创建查找/排序条件并在您的查找语句中使用它们。

Outta my head just to give you an idea:我的头脑只是给你一个想法:

var MyFilter = {};
var MySort = {};
if (req.query.created_at != undefined) {
    MyFilter = { created_at : { $gte : req.query.created_at) } };
}

if (req.query.sortOn != undefined){
    MySort = { req.query.sort : 1 };
}

Post.find(MyFilter)
.sort(MySort)
.exec(function (err, posts) {
    ===do your stuff===
});

https://groups.google.com/forum/#!searchin/mongodb-user/paging%7Csort:relevance/mongodb-user/_Jrv9vI1lDE/Wg0eGV2AkZYJ https://groups.google.com/forum/#!searchin/mongodb-user/paging%7Csort:relevance/mongodb-user/_Jrv9vI1lDE/Wg0eGV2AkZYJ

I just found the same topic in google groups with perfect answer.我刚刚在 google 群组中找到了相同的主题,并给出了完美的答案。

You could try creating a compound index on age and _id, and sort by both fields to get the first three documents.您可以尝试在年龄和 _id 上创建一个复合索引,并按这两个字段进行排序以获取前三个文档。 To get the subsequent set of users, your query should return documents that satisfy either of the following requirements:要获取后续用户集,您的查询应返回满足以下任一要求的文档:

  • have the same age as the last document and have a greater _id or与上一个文档具有相同的年龄并且具有更大的 _id 或
  • have a greater age有更大的年龄

For example (lastAge and lastID are the age and _id of the latest user):例如(lastAge 和 lastID 是最新用户的年龄和 _id):

db.collection.find( { $or : [ { age : lastAge, _id : {$gt : lastID } } , { age : {$gt : lastID } } ] } )

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

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