Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering by several keys in MongoDB

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.

like image 785
Merc Avatar asked Dec 07 '25 09:12

Merc


1 Answers

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.

like image 94
mquandalle Avatar answered Dec 09 '25 22:12

mquandalle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!