Add more fields in the same document for tie-breakers.
Follow with $limit and/or $skip for top-N or pages.
Piece
Required?
Role
Field name
Yes
Key to order by
1 / -1
Yes
Ascending / descending
Extra fields
No
Stable tie-breakers (often _id)
Pseudocode
Pseudocode
docs = all documents from prior stage
sort docs by:
first field (asc or desc)
then second field if values tie
then third field if still tied
...
emit docs in that new order
Reference
Cheat Sheet
Keep these facts handy while ordering pipeline results.
Topic
Detail
Type
Aggregation stage
Syntax
{ $sort: { field: 1 | -1 } }
Ascending
1 (low → high)
Descending
-1 (high → low)
Top-N
$sort then $limit
Pages
$sort → $skip → $limit
Indexes
Best when early ($match then $sort)
Try it
Live Preview
Sort published articles by views ascending or descending.
Seven published articles. Goal: order them by views descending.
Calculation
$match published: true
→ 7 articles (draft dropped)
$sort: { views: -1 }
Compare views high → low:
15200 Node.js + MongoDB
12400 Intro to MongoDB
11300 REST API Design
8900 Aggregation Basics
7800 Express Middleware
6700 Indexing Strategies
5400 Schema Validation
Result: same 7 docs, new order
Code
MongoDB Examples
We use a small articles collection. First sort by views, then sort with a tie-breaker and keep the top 3. Run these in mongosh after inserting the sample data once.
Example 1 — Sample Data
Eight articles with views and a published flag—enough for sort and top-N demos.
Intro to MongoDB 12400 published
Aggregation Basics 8900 published
Node.js + MongoDB 15200 published
Indexing Strategies 6700 published
Draft: Sharding 0 draft
REST API Design 11300 published
Schema Validation 5400 published
Express Middleware 7800 published
Read the important fields like this:
Field
Example
Plain English
views
15200
Primary sort key
published
true
Filter before sorting
title
"REST API Design"
What we show in results
How It Works
Reset once.drop() keeps demos repeatable.
Mixed publish state. One draft is excluded by later $match.
find() shows insert order.$sort will change that next.
Example 2 — Sort by Views
Goal: published articles only, highest views first.
Yes for meaningful pages and top-N lists. Pattern: $match → $sort → $skip → $limit. Without $sort first, skip/limit use arbitrary order.
Yes. Create the field with $set or $addFields first, then $sort on that field—for example sort by lineTotal after $multiply.
When $sort is first in the pipeline or only preceded by $match, MongoDB can use a matching index and avoid an in-memory sort. Otherwise it sorts in memory (disk spill may apply for large sorts).
$sort orders full documents by field values. $sortByCount groups by a field, counts each group, and returns those counts sorted—not a general document sort.