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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With