sort() (Sort Results)

Last updated: 2026-10-09

sort() (Sort Results)

sort() orders cursor results by given fields: `db.users.find().sort({ age: 1, name: -1 })`. Values are 1 for ascending, -1 for descending, applied field by field. Sorting runs server-side — fastest when backed by an index; unsorted-by-index cases sort in memory and can hit the 100MB cap.

CategoryCursor
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.find(<filter>).sort(<sortKey>)

⚙️ Parameters

sort keyField-to-direction mapping, e.g. {age: 1, name: -1}.

Returns:The cursor sorted by the sort key (chainable).

▶ Example

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

// sort: age ascending then name descending, take 3
const result = db.users.find()
  .sort({ age: 1, name: -1 })
  .limit(3)
  .toArray()
result

Output:

[
  { _id: ObjectId('64c8a1b20000000000000001'), name: 'Alice', age: 21 },
  { _id: ObjectId('64c8a1b20000000000000002'), name: 'Bob', age: 25 }
]

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat do 1 and -1 mean in sort?
A1 is ascending, -1 descending — {age: -1} sorts oldest first.
QHow do I sort by multiple fields?
APass several fields in the sort key, e.g. {age: 1, name: -1} — age first, then name.
QWhat if my sort is slow?
AAdd a compound index on the sort fields; indexless sorts use memory, and allowDiskUse() helps with huge results.
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%

🙏 帮我们做得更好

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

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