mongo排序后限制后排序-不起作用 [英] mongo sort after limit after sort - Not working
问题描述
我有一个集合,使用$ query从中可以得到特定类型的用户
然后我需要根据user_id升序对它们进行排序并将其限制为2000
I have a collection, from which i get particular type of users using $query
Then I need sort them according to user_id ascending and limit them to 2000
从这些中我需要最大的user_id,因此我将它们降序排列并限制为1.
From these I need the max user_id, so I sort them in descending order and limit to 1.
但是第二种排序忘记了2000的限制,并通过find()在整个游标上进行排序.
But this second sort forgets the limit of 2000 and sorts over over the entire cursor from find().
有其他解决方法吗?
$cursor = $collection ->find($query) // too many entries
->sort(array('user_id'=>1)) // go ascending
->limit(2000) // got our limited qouta
->sort(array('user_id'=>-1)) // go descending to get max
->limit(1); // the one with max(user_id)
推荐答案
您不能先进行排序,再进行限制,然后进行排序. Cursor对象正是该对象,直到您通过getNext()
迭代到第一个结果(它是手动运行或在foreach
循环内运行)时,它才会运行查询,不仅如此,而且sort
仅仅是对象的一个属性因此,进行两种排序只会覆盖该属性.
Your cannot do a sort and then a limit and then a sort. The Cursor object is exactly that and it will not run the query until you iterate to the first result via getNext()
which is either run manually or within a foreach
loop not only that but sort
is just a property of the object as such making two sorts just overwrites the property.
实现您所寻找的最佳方法是:
The best way to achieve what your looking for is:
$doc = $collection->find($query)->sort(array('user_id' => 1))
->skip(1999)->limit(1)->getNext();
这将始终选择组中最高的user_id
(在此类别的末尾出现),其结果将与执行两种排序相同.
That will always pick the highest user_id
(which occurs at the end in this sort) of the group, which will give off the same results as doing two sorts.
这篇关于mongo排序后限制后排序-不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!