Alex
Alex

Reputation: 2959

How to sort by a specific criteria the top X documents already sorted with mongodb?

It's a bit hard for me to formulate this question. The thing is, I need to get the 100 best rated documents and then sort the result by another criteria.

I'm a beginner with mongodb and I naively tried something like:

db.myCollection
  .find()                                 // get all the data
  .sort({ "statistics.average": -1 })     // sort by rating
  .limit(100)                             // get the 100 best rated
  .sort({ "statistics.foobar": -1 })      // sort the result by the second criteria

But it doesn't work and it looks like the last sort is done on all the data.

How to properly create a query to fit my needs?

Upvotes: 1

Views: 91

Answers (2)

Sede
Sede

Reputation: 61273

Mongo applies the sort before limiting the results regardless of the order you call sort and limit on the cursor but using the .aggregate() method will give the expected result.

db.mycollection.aggregate([
    { "$sort": { "statistics.average": -1 } },
    { "$limit": 100 }, 
    { "$sort": { "statistics.foobar": -1 } }
]) 

Upvotes: 1

undefined_variable
undefined_variable

Reputation: 6228

db.myCollection
  .find()                                 // get all the data
  .sort({ "statistics.average": -1 ,"statistics.foobar": -1 })     // sort by rating followed by foobar
  .limit(100) // get the 100 best rated

Upvotes: 0

Related Questions