← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 6 of 7

sort()

sort orders results ascending with 1 or descending with -1, and can use several fields.

In this page:

  1. sort()
Syntax
javascript
db.collection_name.find(filter).sort({ field: 1 })
db.collection_name.find(filter).sort({ field1: -1, field2: 1 })

sort()

cursor.sort({ field: 1 }) sorts ascending and -1 descending. List several fields to break ties in order. Sorting without an index on large data can be slow or hit the memory limit, so index the sort fields you query often.

Note: Sort keys order matters: { a: 1, b: -1 } sorts by a then b.

Example: sort()

bash
test> db.players.insertMany([
...   { _id: 1, name: "Ada", team: "red", score: 30 }, { _id: 2, name: "Bob", team: "blue", score: 50 },
...   { _id: 3, name: "Cy", team: "red", score: 50 }, { _id: 4, name: "Di", team: "blue", score: 10 }
... ])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.players.find({}, { _id: 0 }).sort({ score: -1, name: 1 })
[
  { name: 'Bob', team: 'blue', score: 50 },
  { name: 'Cy', team: 'red', score: 50 },
  { name: 'Ada', team: 'red', score: 30 },
  { name: 'Di', team: 'blue', score: 10 }
]
test> db.players.find({}, { name: 1, _id: 0 }).sort({ score: -1 }).limit(2)
[ { name: 'Bob' }, { name: 'Cy' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Using asc or desc strings
  2. Forgetting sort with limit for top-N
  3. Sorting large collections without an index
Chapter Summary
  • 1 ascending, -1 descending
  • Multiple keys break ties
  • Index sort fields
  • Combine with limit for top-N
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.