Docs Menu
Docs Home
/ /

$sort (aggregation stage)

$sort

Sorts all input documents and returns them to the pipeline in sorted order.

You can use $sort 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

$sort has the following form:

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort takes a document that specifies the fields to sort by and their sort order. <sort order> can have one of the following values:

Value
Description

1

Sort ascending.

-1

Sort descending.

{ $meta: "textScore" }

Sort by the computed textScore metadata in descending order. For an example, see Text Score Metadata Sort.

When sorting on multiple fields, $sort evaluates sort order from left to right. Documents are first sorted by <field1>, then documents with the same <field1> value are sorted by <field2>.

$sort is a blocking stage, which causes the pipeline to wait for all input data to be retrieved for the blocking stage before processing the data. A blocking stage may reduce performance because it reduces parallel processing for a pipeline with multiple stages. A blocking stage may also use substantial amounts of memory for large data sets.

  • You can sort on a maximum of 32 keys.

  • Providing a sort pattern with duplicate fields causes an error.

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

The $sort operation is not a "stable sort," which means that documents with equivalent sort keys are not guaranteed to remain in the same relative order in the output as they were in the input.

If the field specified in the sort criteria does not exist in two documents, then the value on which they are sorted is the same. The two documents may be returned in any order.

If consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the _id field in your sort query.

Consider the movies collection in the sample_mflix sample dataset. The following command sorts movies released in 1925 or 1926 by year in ascending order:

db.movies.aggregate( [
{ $match: { year: { $in: [ 1925, 1926 ] } } },
{ $sort: { year: 1 } },
{ $project: { _id: 0, title: 1, year: 1 } }
] )

Because the year field has duplicate values for 1925 and 1926, documents with the same value may sort differently across executions. For example, two runs of the previous command produce different orderings:

[
{ title: "Clash of the Wolves", year: 1925 },
{ title: "Lady Windermere's Fan", year: 1925 },
{ title: "Grass: A Nation's Battle for Life", year: 1925 },
{ title: "Beau Geste", year: 1926 },
{ title: "The Black Pirate", year: 1926 },
{ title: "Ella Cinders", year: 1926 },
{ title: "For Heaven's Sake", year: 1926 },
{ title: "The Son of the Sheik", year: 1926 },
{ title: "The Strong Man", year: 1926 }
]
[
{ title: "Lady Windermere's Fan", year: 1925 },
{ title: "Grass: A Nation's Battle for Life", year: 1925 },
{ title: "Clash of the Wolves", year: 1925 },
{ title: "The Strong Man", year: 1926 },
{ title: "The Black Pirate", year: 1926 },
{ title: "Ella Cinders", year: 1926 },
{ title: "Beau Geste", year: 1926 },
{ title: "The Son of the Sheik", year: 1926 },
{ title: "For Heaven's Sake", year: 1926 }
]

An operation sorts values for year in ascending order, but the order of the documents containing duplicate values for year is not the same. For example, duplicate values for 1925 and 1926.

To achieve a consistent sort, add a field that contains only unique values to the sort. The following command sorts on both the year field and the _id field:

db.movies.aggregate( [
{ $match: { year: { $in: [ 1925, 1926 ] } } },
{ $sort: { year: 1, _id: 1 } }
] )

The _id field always contains unique values and the sort order is consistent for multiple sort executions.

When MongoDB sorts documents by an array-value field, the sort key depends on whether the sort is ascending or descending:

  • In an ascending sort, the sort key is the lowest value in the array.

  • In a descending sort, the sort key is the highest value in the array.

The query filter does not affect sort key selection.

For example, consider these documents from the movies collection in the sample_mflix sample dataset:

{
_id: ObjectId("573a1395f29313caabce166c"),
title: "The Comancheros",
genres: [ "Action", "Western", "Adventure" ]
}
{
_id: ObjectId("573a1391f29313caabcd8521"),
title: "The Son of the Sheik",
genres: [ "Adventure", "Drama" ]
}

The following queries sort the documents by the genres field in ascending and descending order:

// Ascending sort
db.movies.aggregate( [
{
$match: {
title: { $in: [
"The Comancheros", "The Son of the Sheik"
] }
}
},
{
$sort: { genres: 1 }
}
] )
// Descending sort
db.movies.aggregate( [
{
$match: {
title: { $in: [
"The Comancheros", "The Son of the Sheik"
] }
}
},
{
$sort: { genres: -1 }
}
] )

Both of the preceding queries return The Comancheros first because Action and Western are the lowest and highest entries in its genres array, respectively.

When you filter and sort by a field that contains an array, the filter does not affect the value used as the sort key. The sort always considers all array values as potential sort keys.

For example, the following query finds movies whose genres array includes "Drama" or "Western" and sorts the results by genres in ascending order:

db.movies.aggregate( [
{
$match: {
title: { $in: [
"The Comancheros", "The Son of the Sheik"
] },
genres: { $in: [ "Drama", "Western" ] }
}
},
{
$sort: { genres: 1 }
}
] )

The sort is ascending. The sort key is the first value in the genres array when sorted alphabetically:

  • In The Comancheros, the first genres element is Action. This value is used as the sort key even though it does not match the filter { genres: { $in: [ "Drama", "Western" ] } }.

  • In The Son of the Sheik, the first genres element is Adventure. Similarly, this operation uses Adventure as the sort key even though it does not match the filter.

The query returns The Comancheros first.

Tip

Sort only by Matched Values

To only consider matched values as potential sort keys, you can generate a new field containing the matched values and sort on that field. For more information, see these pipeline stages and expressions:

When a $sort precedes a $limit and there are no intervening stages that modify the number of documents, the optimizer can coalesce the $limit into the $sort. This allows the $sort operation to only maintain the top n results as it progresses, where n is the specified limit, and ensures that MongoDB only needs to store n items in memory. This optimization still applies when allowDiskUse is true and the n items exceed the aggregation memory limit.

Optimizations are subject to change between releases.

Pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. These temporary files last for the duration of the pipeline execution and can influence storage space on your instance.

Individual find and aggregate commands can override the allowDiskUseByDefault parameter by either:

  • Using { allowDiskUse: true } to allow writing temporary files out to disk when allowDiskUseByDefault is set to false

  • Using { allowDiskUse: false } to prohibit writing temporary files out to disk when allowDiskUseByDefault is set to true

Note

For MongoDB Atlas, it is recommended to configure storage auto-scaling to prevent long-running queries from filling up storage with temporary files.

If your Atlas cluster uses storage auto-scaling, the temporary files may cause your cluster to scale to the next storage tier.

For additional details, see Aggregation Pipeline Limits.

The $sort operator can use an index when it is the first stage in a pipeline or is preceded only by a $match stage.

When you use $sort on a sharded cluster, each shard sorts its result documents using an index where available. Then the mongos or one of the shards performs a streamed merge sort.

The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

For each sort field, set the value to 1 for ascending or -1 for descending. For example:

db.movies.aggregate(
[
{ $sort: { year: -1, title: 1 } },
{ $limit: 5 }
]
)

This operation sorts documents in the movies collection descending by year, then ascending by title, and returns the first five results.

When comparing values of different BSON types in sort operations, MongoDB uses the following comparison order, from lowest to highest:

  1. MinKey (internal type)

  2. Null

  3. Numbers (ints, longs, doubles, decimals)

  4. Symbol, String

  5. Object

  6. Array

  7. BinData

  8. ObjectId

  9. Boolean

  10. Date

  11. Timestamp

  12. Regular Expression

  13. JavaScript Code

  14. JavaScript Code with Scope

  15. MaxKey (internal type)

For details on the comparison/sort order for specific types, see Comparison/Sort Order.

Note

$text provides text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search.

The following example uses the movies collection in the sample_mflix sample dataset. Before running it, create a text index on the plot field:

db.movies.createIndex( { plot: "text" } )

For a pipeline that includes $text, you can sort by descending relevance score using the { $meta: "textScore" } expression. In the { <sort-key> } document, set the { $meta: "textScore" } expression to an arbitrary field name. The field name is ignored by the query system. For example:

db.movies.aggregate(
[
{ $match: { $text: { $search: "pirate" } } },
{ $sort: { score: { $meta: "textScore" }, year: -1 } },
{ $limit: 5 }
]
)

This operation matches documents with $text, then sorts descending by "textScore" metadata and by year, and returns the first five results. The score field name in the sort document is ignored by the query system. The projection doesn't include the "textScore" metadata and does not return the metadata as part of the matching documents. See $meta for more information.

The C# examples on this page use the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started in the MongoDB .NET/C# Driver documentation.

The following Movie class models the documents in the sample_mflix.movies collection:

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string Title { get; set; } = null!;
[BsonElement("year")]
public int? Year { get; set; }
[BsonElement("runtime")]
public int? Runtime { get; set; }
[BsonElement("rated")]
public string? Rated { get; set; }
[BsonElement("metacritic")]
public int Metacritic { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("type")]
public string? Type { get; set; }
[BsonElement("cast")]
public string[]? Cast { get; set; }
[BsonElement("directors")]
public string[]? Directors { get; set; }
[BsonElement("writers")]
public string[]? Writers { get; set; }
[BsonElement("imdb")]
public ImdbData? Imdb { get; set; }
}

To use the MongoDB .NET/C# driver to add a $sort stage to an aggregation pipeline, call the Sort() method on a PipelineDefinition object.

The following example creates a pipeline stage that first filters for Movie documents where Metacritic equals 100, then sorts the results in descending order by the Year field and ascending order by the Title field:

var pipeline = new EmptyPipelineDefinition<Movie>()
.Match(Builders<Movie>.Filter.Eq(m => m.Metacritic, 100))
.Sort(Builders<Movie>.Sort.Combine(
Builders<Movie>.Sort.Descending(m => m.Year),
Builders<Movie>.Sort.Ascending(m => m.Title)));
{ "_id" : "...", "title" : "Boyhood", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 2014 }
{ "_id" : "...", "title" : "Best Kept Secret", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : "..." }
{ "_id" : "...", "title" : "Fanny and Alexander", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 1982 }
{ "_id" : "...", "title" : "The Godfather", "metacritic" : 100, "rated" : "R", "runtime" : 175, "year" : 1972 }
{ "_id" : "...", "title" : "The Conformist", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 1970 }
{ "_id" : "...", "title" : "The Leopard", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 1963 }
{ "_id" : "...", "title" : "Lawrence of Arabia", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 1962 }
{ "_id" : "...", "title" : "The Wizard of Oz", "metacritic" : 100, "rated" : "...", "runtime" : "...", "year" : 1939 }

To use the MongoDB Node.js driver to add a $sort stage to an aggregation pipeline, use the $sort operator in a pipeline object.

The following example creates a pipeline stage that sorts the input movie documents first in descending order by the year field, and then in ascending order by the title field. The example then runs the aggregation pipeline:

const pipeline = [{ $sort: { year: -1, title: 1 } }];
const cursor = collection.aggregate(pipeline);
return cursor;

For full aggregation examples that use $sort, see Complete Aggregation Pipeline Tutorials.

Back

$skip

On this page