Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in MongoDB's aggregation framework

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?

like image 724
Assaf Lavie Avatar asked Apr 07 '13 15:04

Assaf Lavie


1 Answers

From the docs:

As python dictionaries don’t maintain order you should use SON or collections.OrderedDict where explicit ordering is required eg "$sort"

from bson.son import SON
db.users.aggregate([
    {"$sort": SON([("posts", 1), ("age", -1)])}
])
like image 73
JohnnyHK Avatar answered Oct 20 '22 19:10

JohnnyHK