How to Sort Array in MongoDB: Syntax and Examples
To sort an array inside a MongoDB document, use the
$sortArray operator within an aggregation pipeline stage like $project or $set. For updating arrays, use the $push operator with $each and $sort modifiers to reorder array elements.Syntax
MongoDB provides different ways to sort arrays inside documents depending on the operation:
- Aggregation Pipeline: Use
$sortArray(MongoDB 5.2+) or$sortinside$projector$setto reorder array elements. - Update Operation: Use
$pushwith$eachand$sortmodifiers to sort an array during update.
Example syntax for aggregation:
{ $set: { sortedArray: { $sortArray: { input: "$arrayField", sortBy: 1 } } } }Example syntax for update:
{ $push: { arrayField: { $each: [], $sort: 1 } } }mongodb
{
$set: {
sortedArray: { $sortArray: { input: "$arrayField", sortBy: 1 } }
}
}Example
This example shows how to sort an array field named scores inside documents using an aggregation pipeline with $set and $sortArray. It sorts the array in ascending order.
mongodb
db.students.aggregate([
{
$set: {
sortedScores: { $sortArray: { input: "$scores", sortBy: 1 } }
}
}
])Output
[
{
_id: ObjectId("..."),
name: "Alice",
scores: [88, 75, 92],
sortedScores: [75, 88, 92]
},
{
_id: ObjectId("..."),
name: "Bob",
scores: [95, 85, 90],
sortedScores: [85, 90, 95]
}
]
Common Pitfalls
Common mistakes when sorting arrays in MongoDB include:
- Trying to use
$sortdirectly on arrays outside aggregation or update contexts. - Not using
$eachwith$pushwhen sorting arrays during updates. - Using older MongoDB versions that do not support
$sortArray(added in 5.2).
Always check your MongoDB version and use the correct operator for your use case.
mongodb
/* Wrong: Trying to sort array directly in update without $each */ db.collection.updateOne( { _id: 1 }, { $push: { scores: { $sort: 1 } } } ) /* Right: Use $each with $sort */ db.collection.updateOne( { _id: 1 }, { $push: { scores: { $each: [], $sort: 1 } } } )
Quick Reference
| Operation | Syntax Example | Description |
|---|---|---|
| Aggregation sort array | { $set: { sorted: { $sortArray: { input: "$arr", sortBy: 1 } } } } | Sorts array ascending inside aggregation |
| Update sort array | { $push: { arr: { $each: [], $sort: -1 } } } | Sorts array descending during update |
| Legacy aggregation | { $project: { sorted: { $map: { input: { $sortArray: "$arr" }, as: "x", in: "$x" } } } } | Alternative sorting in older versions |
Key Takeaways
Use $sortArray in aggregation pipelines to sort arrays inside documents.
Use $push with $each and $sort modifiers to sort arrays during updates.
Check MongoDB version; $sortArray requires version 5.2 or newer.
Avoid using $sort directly on arrays outside aggregation or update contexts.
Sorting arrays in MongoDB requires specific operators depending on the operation.