Assaf Lavie
Assaf Lavie

Reputation: 76123

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?

Upvotes: 5

Views: 1966

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

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)])}
])

Upvotes: 7

Related Questions