MongoDB $ skip + $ limit在查找结果中重复 [英] MongoDB $skip + $limit duplicates in find results

查看:285
本文介绍了MongoDB $ skip + $ limit在查找结果中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Django应用程序的AJAX分页聚合查询中使用了 $ skip $ limit 。以下是我的代码示例:

I'm using $skip and $limit in my aggregation queries for AJAX pagination in my Django app. Here is an example of my code:

art_cursor = Articles.objects.aggregate({'match': {'ntype': {'$in': [1,6]}}},
    {'$group': {'_id': {'title': '$title'}}},
    {'$sort': {'_id.title': -1}},
    {'$limit': 51 * page}, {'$skip': 51 * (page-1)},
    allowDiskUse=True)

所以我有一些排序的文章池,想​​要获得一个独特的部分对于每个页面,当用户向下滚动时。

So I've got some sorted articles pool and want to get an unique portion of them for every page, when user scrolls down.

但是有些文章在不同的页面上重复,这意味着如果我将上面的代码放在范围(1 ,6)循环(用于将所有文章从1到5页),然后结果数组中的一些文章将被重复。

But some of articles are repeated on different pages, that means if I'll put above code in range(1,6) loop (for getting all the articles from 1 to 5 pages), then some articles in result array will be repeated.

哪种解决方法可能是或者另一种方式我可以做这样的事情?

Which workaround could be done for it, or maybe another way I can do such thing?

UPD1
btw,如果我删除 $排序操作 - 结果数组中没有重复。我不知道为什么

UPD1 btw, if I remove $sort operation - there are no duplicates in result array. I have no idea why

推荐答案

好的,问题是关于 $ sort + $限制 MongoDB优化。当我们在$ sort之后得到$ limit时,MongoDB优化器只对我们得到$ limit结果的对象进行排序。

Ok, the problem is about $sort + $limit MongoDB optimization. When we got $limit right after $sort, MongoDB optimizer sorting only objects we got in $limit result.

源(MongoDB文档): https://docs.mongodb.com/manual/core/aggregation-pipeline -optimization /#agg-sort-limit-coalescence

Source (MongoDB docs): https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/#agg-sort-limit-coalescence

这篇关于MongoDB $ skip + $ limit在查找结果中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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