简体   繁体   English

MongoDB API分页

[英]MongoDB API pagination

Imagine situation when a client has feed of objects with limit 10. 想象一下当客户端提供具有限制10的对象时的情况。
When the next 10 are required it sends request with skip 10 and limit 10. 当需要接下来的10个时,它会发送跳过10并限制为10的请求。

But what if there are some new objects were added (or deleted) to collection since the 1st request with offset == 0. 但是,如果第一个请求偏移量== 0,则会有一些新对象被添加(或删除)到集合中。

Then on 2nd request (with offset == 10) response may have wrong objects order. 然后在第二次请求(带偏移== 10)时,响应可能有错误的对象顺序。

Sorting on time of their creation does not work here, because I have some feeds which are formed on sorting via some numeric field. 对它们的创建时间进行排序在这里不起作用,因为我有一些通过某些数字字段排序时形成的提要。

It really depends on what you want the result to be. 这实际上取决于你想要的结果。

If you want the original objects in their original order regardless of Delete and Add operations then you need to make a copy of the list (or at least of the order) and then page through that. 如果您希望原始对象按原始顺序而不管删除和添加操作,那么您需要复制列表(或至少是订单),然后翻阅它。 Copy every Id to a new collection that doesn't change once the page has loaded and then paginate through that. 将每个Id复制到一个新的集合,该集合在页面加载后不会更改,然后通过它进行分页。

Alternatively, and perhaps more likely, what you want is to see the next 10 after the last one in the current set including any Delete or Add operations that have take place since. 或者,也许更有可能的是,你想要的是看到当前集合中最后一个之后的10个,包括之后发生的任何删除或添加操作。 For this, you can use the sorted order in which you are viewing them and a filter, $gt whatever the last item was. 为此,您可以使用您正在查看它们的排序顺序和过滤器,$ gt,无论最后一项是什么。 BUT that doesn't work when there are duplicates in the field on which you are sorting. 但是,当您要排序的字段中存在重复项时,这不起作用。 To get around that you will need to index on that field PLUS some other field which is unique per record, for example, the _id field. 为了解决这个问题,你需要在该字段上编制索引PLUS其他每个记录唯一的字段,例如_id字段。 Now, you can take the last record in the first set and look for records that are $eq the indexed value and $gt the _id OR are simply $gt the indexed value. 现在,您可以获取第一组中的最后一条记录,并查找$ eq为索引值的记录,$ gt,_id OR只是$ gt索引值。

You can add a time field like created_at or updated_at. 您可以添加一个时间字段,如created_at或updated_at。 It must updated when ever the document is created or modified and the field must be unique. 在创建或修改文档时必须更新它,并且该字段必须是唯一的。

Then query the DB for the range of time using $gte and $lte along with a sort on this time field. 然后使用$ gte和$ lte 以及此时间字段的排序查询数据库中的时间范围。

This ensures that any changes made outside the time window will not get reflected in the pagination, provided that the time field does not have duplicates. 这可确保在时间窗口外进行的任何更改都不会反映在分页中,前提是时间字段没有重复项。 Most probably if you include microtime, duplicates wont happen. 最有可能的是,如果你包括microtime,重复不会发生。

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

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