$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.

CategoryUpdate Modifier
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $push: { <array field>: { $each: [ <value> ], $sort: <1 or -1> } } }

⚙️ Parameters

array fieldThe array field to sort.
sort direction1 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏