$sort (Sort)

Last updated: 2026-10-09

$sort (Sort)

$sort orders pipeline documents by specified fields: 1 ascending, -1 descending, with multi-field sorts supported. Place it near the end, since intermediate stages may reorder documents. To sort with an index, put $match first. Large sorts exceed the default 100MB memory limit and fail unless allowDiskUse is enabled.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $sort: { <field1>: <1 or -1>, <field2>: <1 or -1> } }

⚙️ Parameters

sort keyField names mapped to 1 (ascending) or -1 (descending); multiple fields compare in written order.

Returns:Sorted document stream

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $sort: highest score first, name ascending on ties
db.scores.aggregate([
  { $sort: { score: -1, name: 1 } }
])

Output:

{ "name": "Alice", "score": 98 }
{ "name": "Bob", "score": 92 }

📌 Notes

📚 Related Tutorials

❓ FAQ

QHow does $sort handle multiple fields?
AFields compare in written order: first by the first field, then by the second when values tie.
QCan $sort use an index?
AWhen the sort key matches an index and the stage is first or follows $match, the index avoids an in-memory sort.
QWhat if $sort hits the memory limit?
APass allowDiskUse: true in the aggregate options to spill to disk.
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%

🙏 帮我们做得更好

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

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