$sort (Sort Array, Update)
Last updated: 2026-10-09
$sort (Sort Array, Update)
$sort as an update modifier orders array elements after $push. `{ $push: { scores: { $each: [85], $sort: -1 } } }` sorts descending. Compose with $slice to sort then trim, keeping the Top N. It is an array-update modifier only, distinct from the query sort() method.
| Category | Update Modifier |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $push: { <array field>: { $each: [ <value> ], $sort: <1 or -1> } } }
⚙️ Parameters
| array field | The array field to sort. |
|---|---|
| sort direction | 1 ascending, -1 descending. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $sort: sort descending after push
// 1 asc, -1 desc
db.rankings.updateOne(
{ _id: 1 },
{ $push: { scores: { $each: [85], $sort: -1 } } }
)
// With $slice: keep the Top 3
db.rankings.updateOne(
{ _id: 1 },
{ $push: { scores: { $each: [85], $sort: -1, $slice: 3 } } }
)
Output:
// scores sort descending after appending; the second query trims to the Top 3
📌 Notes
- Works only as a $push modifier
- Combine with $slice for a Top-N list
- Unrelated to the query sort() method
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between the update $sort and query sort()?
AUpdate $sort orders the array elements; sort() orders the returned documents.
QHow do $sort and $slice combine?
A$push: { $each: [...], $sort: -1, $slice: 10 } — sort first, then trim.
QCan it sort by a nested field?
AYes, $sort supports the { field: 1 } object form.