3

I would like to order a collection based on several keys. E.g.:

db.collection.find().sort( { age: -1, score: 1 } );

This is all fine and dandy. However, I would like to guarantee that age comes first, and score comes next.

In Javascript, the order in which an object keys are listed is not guaranteed.

The explanation of sort in the official MongoDb documentation is not exactly clear.

So... is the way I showed actually reliable in terms of order in which the arguments are taken?

Merc.

Community
  • 1
  • 1
Merc
  • 16,277
  • 18
  • 79
  • 122
  • Will you be using numerical field names? – Sammaye Jul 10 '13 at 12:28
  • Then you don't have a problem, the problem comes with the difference between numeric keys and alphanumeric keys, if all keys are alphanumeric they should be ordered as they are read – Sammaye Jul 10 '13 at 12:55

2 Answers2

3

The syntax you use only works if your JavaScript implementation preserves the order of keys in objects. Most do, most of the time, but it's up to you to be sure.

For the Nodejs official driver, there is an alternate form that works with an Array:

db.collection.find().sort([[age, -1], [score, 1]]);

Drivers for other languages might have something similar.

mquandalle
  • 2,600
  • 20
  • 24
  • I would love this to work. However, `db.collection.find().sort([ { age: -1 }, { score: 1 } ]);` doesn't seem to _actually_ work in the mongo shell – Merc Jul 10 '13 at 12:23
  • `db.collection.find().sort([[age: -1], [score: 1]]);` isn't valid JavaScript. – WiredPrairie Jul 10 '13 at 12:41
  • That syntax is valid, but it doesn't do a thing on the MongoDB shell. It's node-mongodb-native specific, please mention that in your answer. – Derick Jul 10 '13 at 14:17
0

The aggregation documentation actually provides a little bit more information on the subject, in which it states:

db.users.aggregate(
    { $sort : { age : -1, posts: 1 } }
);

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field

Which would indicate that the .sort() method functions in the same way.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176