Docs Menu

Docs HomeView & Analyze DataMongoDB Compass

Sort the Returned Documents

If the query bar displays the Sort option, you can specify the sort order of the returned documents.

You can sort the returned documents for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB

  • MongoDB Community: The source available, free-to-use, and self-managed version of MongoDB

To learn more about sorting returned documents for deployments hosted in MongoDB Atlas, see Sort Query Results.

To set the sort order:

  1. In the Query Bar, click Options.

  2. Enter the sort document into the Sort field.

    • To specify ascending order for a field, set the field to 1 in the sort document.

    • To specify descending order for a field, set the field and -1 in the sort documents.

    Example

    The following sort document sorts results first by year in descending order, and within each year, sort by name in ascending order.

    { year: -1, name: 1 }

    As you type, the Find button is disabled and the Sort label turns red until a valid query is entered.

  3. Click Find to run the query and view the updated results.

To clear the query bar and the results of the query, click Reset.

See the sort entry in the MongoDB Manual.

$sort corresponds to the ORDER BY ... clause in a SQL SELECT statement.

Example

You have 3,235 articles. You would like to see a list of articles sorted alphabetically by headline.

SQL
SELECT * FROM article
ORDER BY headline ASC;
MongoDB Aggregation
db.article.aggregate(
{ $sort : { headline : 1 } }
);
Compass Sort Option
$sort : { headline : 1 }
←  Set Which Fields Are ReturnedAdjust Maximum Time for Query Operations →