$sortArray (Sort Elements Within Array)
Last updated: 2026-10-09
$sortArray (Sort Elements Within Array)
$sortArray sorts the elements inside an array and is new in MongoDB 5.2. Scalar arrays use a plain 1 (ascending) or -1 (descending); object arrays specify sort keys with { field: 1/-1 } or the array form [ [ 'field', 1 ] ] for multi-key sorting. Typical uses: ordering comments by time descending or products by price ascending before display. It returns a new array without mutating the source; an empty sortBy object throws an error.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $sortArray: { input: <array>, sortBy: <sortSpec> } }
⚙️ Parameters
| input | The array to sort. |
|---|---|
| sortBy | The sort specification: 1/-1 for scalar arrays; { field: 1/-1 } or [ [ 'field', 1 ] ] for object arrays. |
Returns:A new array with sorted elements
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $sortArray: sort items by price ascending
db.orders.aggregate([
{ $project: {
sorted: { $sortArray: { input: '$items', sortBy: { price: 1 } } }
} }
])
Output:
{ '_id': 1, 'sorted': [ { 'sku': 'B', 'price': 5 }, { 'sku': 'A', 'price': 9 } ] }
📌 Notes
- Requires MongoDB 5.2+; on older versions use $unwind, $sort, then $group
- Elements missing the sort key field sort to the end
- An empty sortBy object throws; null elements always sort last
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes $sortArray support multi-field sorting?
AYes — use the form [ [ 'field1', 1 ], [ 'field2', -1 ] ].
QDoes it work on older MongoDB?
ANew in 5.2; on older versions $unwind, sort with $sort, then re-group.
QWhere do elements missing the key sort?
AThey sort to the end of the array.