51

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.

Query 1

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

Query 2

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

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"
}
Community
  • 1
  • 1
hughesdan
  • 3,019
  • 12
  • 57
  • 80

2 Answers2

83

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

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

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

Proof in docs: link

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

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’.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • The link just says the two statements are equivalent, not saying calling sort before limit. Any more obvious proof ? – Lewis Chan Apr 03 '20 at 09:47
  • I added the info from the docs to the answer. See the second sentence. – JohnnyHK Apr 03 '20 at 13:04
  • Does this do a full sort or does it optimize and only apply a partial sort? – Walton Apr 14 '21 at 16:52
  • Another option to control when the sort is executed could be to use the aggregation framework: https://docs.mongodb.com/manual/reference/operator/aggregation/sort/ – Braulio May 31 '21 at 08:26
0

I had troubled using the limit, had to remove the $ before it:

MyCollection.find({ "exampleQuery._id": "exampleId123xx }, { $sort: { requestDate: -1 }, limit: 3 });
maudulus
  • 10,627
  • 10
  • 78
  • 117