基于时间的链接排序和限制问题 [英] Chaining time-based sort and limit issue

查看:78
本文介绍了基于时间的链接排序和限制问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在玩mongo和sort/limit时遇到了一些奇怪的行为(即,它们是恕我直言,违反直觉的).

Lately I've encountered some strange behaviours (i.e. meaning that they are, IMHO, counter-intuitive) while playing with mongo and sort/limit.

假设我有以下收藏:

> db.fred.find()
{ "_id" : ObjectId("..."), "record" : 1, "time" : ISODate("2011-12-01T00:00:00Z") }
{ "_id" : ObjectId("..."), "record" : 2, "time" : ISODate("2011-12-02T00:00:00Z") }
{ "_id" : ObjectId("..."), "record" : 3, "time" : ISODate("2011-12-03T00:00:00Z") }
{ "_id" : ObjectId("..."), "record" : 4, "time" : ISODate("2011-12-04T00:00:00Z") }
{ "_id" : ObjectId("..."), "record" : 5, "time" : ISODate("2011-12-05T00:00:00Z") }

我想要按时间顺序检索记录"之前的2条记录:4加上记录4(即记录2,记录3和记录4)

What I would like is retrieving, in time order, the 2 records previous to "record": 4 plus record 4 (i.e. record 2, record 3 and record 4)

我天真地打算沿着某处奔跑:

Naively I was about running something along:

db.fred.find({time: {$lte: ISODate("2011-12-04T00:00:00Z")}}).sort({time: -1}).limit(2).sort({time: 1})

但它不能按我预期的方式工作:

but it does not work the way I expected:

{ "_id" : ObjectId("..."), "record" : 1, "time" : ISODate("2011-12-01T00:00:00Z") }
{ "_id" : ObjectId("..."), "record" : 2, "time" : ISODate("2011-12-02T00:00:00Z") }

我在想结果应该是记录2,记录3和4.

I was thinking that the result would have been record 2, record 3 and 4.

根据我的回忆,似乎第2类确实适用于限制:

From what I recollected, it seems that the 2 sort does apply before limit:

  sort({time: -1})                          => record 4, record 3, record 2, record 1
  sort({time: -1}).limit(2)                 => record 4, record 3
  sort({time: -1}).limit(2).sort({time: 1}) => record 1, record 2

即,就像将第二种排序应用于find(即整个集合)返回的游标,然后仅应用限制.

i.e it's like the second sort was applied to the cursor returned by find (i.e. the whole set) and then only, the limit is applied.

这是我的错误,如何实现预期的行为?

What is my mistake here and how can I achieve the expected behavior?

顺便说一句:在Ubuntu 11.01上运行mongo 2.0.1

BTW: running mongo 2.0.1 on Ubuntu 11.01

推荐答案

在同一查询中多次应用sort()在这里没有意义.有效的排序将从上一个sort()调用中获取.所以

Applying sort() to the same query multiple times makes no sense here. The effective sorting will be taken from the last sort() call. So

sort({time: -1}).limit(2).sort({time: 1})

sort({time: 1}).limit(2)

这篇关于基于时间的链接排序和限制问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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