Sorting
Sorting: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 28 of 100
Sorting
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Query Operators
What is this?
sort orders cursor results. Pass { field: 1 } for ascending or { field: -1 } for descending. You can sort by multiple fields. Indexes can support sort without in-memory work.
Why should you care?
Feeds show newest first, leaderboards show score descending, and catalogs sort by price — users expect stable ordering.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.products.insertMany([
{ name: "A", price: 500, rating: 4.2 },
{ name: "B", price: 500, rating: 4.8 },
{ name: "C", price: 300, rating: 4.5 }
])
db.products.find().sort({ price: 1, rating: -1 })
db.products.find().sort({ rating: -1 }).limit(2)
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- First sort: lowest price first; for same price, higher rating first — order C, then B, then A.
- Second query returns the top two ratings.
- limit pairs naturally with sort.
Practice next
- Insert the three products.
- Run both sorts and write down the order.
- Create index { price: 1, rating: -1 } and explain the first query.
- Sort name alphabetically.
- Combine sort with skip for pages.
Remember
1 = ascending, -1 = descending. Multi-field sort breaks ties. Index sorts for hot paths.
App Store-like ranking
A learning app sorts courses by rating desc then enrollments desc.
Outcome: Home screen shows strongest courses first.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!