您如何告诉Mongo在限制结果之前对集合进行排序? [英] How do you tell Mongo to sort a collection before limiting the results?

查看:69
本文介绍了您如何告诉Mongo在限制结果之前对集合进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个集合中选择最新的文档.这个问题的答案 mongodb:如何获取最近的N条记录? /a>表示查询中的操作顺序很重要.但是,情况似乎并非如此(也许自Mongo 2.4发布以来).我已经尝试了以下两个查询,看来Mongo首先应用了限制,然后执行了排序.

I want to select the most recent documents from a collection. The answer from this question mongodb: how to get the last N records? suggests that the order of operations in the query matters. However this does not appear to be the case (perhaps since Mongo 2.4 was released). I've tried both of the following queries and it appears that Mongo first applies the limit and then performs the sort.

查询1

myCollection.find().sort( { '$date': 1 }).limit(50, callback);

查询2

myCollection.find().limit(50).sort( { '$date': 1 }, callback);

告诉mongo首先排序然后限制第二的正确查询是什么?

What would be the correct query to tell mongo to sort first and limit second?

编辑---这是集合中的示例文档

EDIT --- Here's a sample document from the collection

{
  _id: ObjectId("517eb0dddbab79c74700005d"),
  audioFiles: [
    {
      audioFileName: "C64FEFA8-DD43-40A1-8996-35948F3438BF-6896-0000027BD4A59D91",
      audioLanguage: "English",
      date: ISODate("2013-05-21T16:23:04.006Z"),
      flag: "1",
      user: "36C4DEB6-C13D-4211-94B5-CC4DD993ECF1-6896-00000278FA7B08EC"
    },
    {
      audioFileName: "994B6DF6-73B5-458F-912A-FF67A84534B2-23532-0000020000000000",
      audioLanguage: "English",
      date: ISODate("2013-05-27T10:45:04.107Z"),
      flag: "1",
      user: "9D7BB3F4-371B-4F2A-8DA2-0C4CE8B4E16D-974-0000000000000000"
    }
  ],
  date: ISODate("2013-04-29T17:41:49.101Z"),
  imageFileName: "SteamLokomotive0498",
  random: 0.6750695831142366,
  thumbFileName: "SteamLokomotive0498_150x150",
  user: "62923D8E-00CE-4F0C-AECA-3010D78FC9CE-226-0000000000000000",
  userLanguagePref: "Cantonese"
}

推荐答案

问题是您需要对date而不是$date进行排序.

The problem is that you need to sort on date instead of $date.

myCollection.find().sort({date: 1}).limit(50, callback);

无论您在光标上调用sortlimit的顺序如何,Mongo都会在限制结果之前应用排序.

Mongo applies the sort before limiting the results regardless of the order you call sort and limit on the cursor.

文档中的证明:链接

db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )

这两个语句是等效的;即您链接的顺序 limit()和sort()方法并不重要.两种说法 返回由升序确定的前五个文档 订购名称".

The two statements are equivalent; i.e. the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on ‘name’.

这篇关于您如何告诉Mongo在限制结果之前对集合进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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