Aggregation Framework - $sort

Overview

The $sort pipeline operator sorts its input documents.

Specification

db.<collection-name>.aggregate(
    { $sort : { <sort-key> } }
);

$sort requires a sort key. Sort key specifications are exactly the same as those for
indexing (see Indexes - Basics and Indexes - Compound Keys Indexes). A sort key is a series of field-value pairs, each of which specifies a 1 or -1 for its value to indicate an ascending or descending sort, as shown by this example:

db.sortex.aggregate(
    { $sort : { b : -1, a: 1 } }
);

Here, the output will be the sorted collection, sorted by "b" descending, and "a" ascending.

Notes

The $sort operator cannot produce any output documents until it has seen all of its input. It will exhaust the prior pipeline operator's output, sort what it has received, and then be ready to produce output.

At the present time, sorts must fit in memory, so sorting a large input stream may not work.

Follow @mongodb

MongoDB Pittsburgh - May 15
MongoNYC - May 23
MongoDB Paris - Jun 14
MongoDB UK - Jun 20
MongoDC - June 26


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus