The docs for MongoDB seem to suggest that in order to sort the results of an aggregate
call you should specify a dictionary/object like this:
db.users.aggregate(
{ $sort : { age : -1, posts: 1 } }
);
This is supposed to sort by age
and then by posts
.
What do I do if I want to sort by posts
and then by age
? Changing the order of the keys seems to have no effect, probably because this is a JS object's properties. In other words, sorting, it seems, is always according to the lexical order of the keys, which seems rather odd as a design choice...
Am I missing something? Is there a way to specify an ordered list of keys to sort by?
From the docs:
As python dictionaries don’t maintain order you should use
SON
orcollections.OrderedDict
where explicit ordering is required eg "$sort"
from bson.son import SON
db.users.aggregate([
{"$sort": SON([("posts", 1), ("age", -1)])}
])
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