MongoDB $sort Stage

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $sort?

$sort is a MongoDB aggregation stage that reorders documents by one or more fields. Use 1 for ascending and -1 for descending.

Remember
$sort = "reorder documents by field(s)"

{ $sort: { views: -1 } }     // high → low
{ $sort: { title: 1 } }      // A → Z

1  → ascending
-1 → descending

multi-field → first key wins, next breaks ties
for top-N → $sort then $limit
for pages → $sort → $skip → $limit

find().sort(...) → similar idea outside aggregation
UsePrefer
Top-N / leaderboard$sort + $limit
Offset pagination$sort → $skip → $limit
Group counts sorted$sortByCount

How to Use $sort in MongoDB

Filter first when you can, then sort, then skip/limit if you need a page or top-N.

  1. Optionally filter with $match.
  2. Add { $sort: { field: 1 | -1 } }.
  3. Add more fields in the same document for tie-breakers.
  4. Follow with $limit and/or $skip for top-N or pages.
PieceRequired?Role
Field nameYesKey to order by
1 / -1YesAscending / descending
Extra fieldsNoStable 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

Cheat Sheet

Keep these facts handy while ordering pipeline results.

TopicDetail
TypeAggregation stage
Syntax{ $sort: { field: 1 | -1 } }
Ascending1 (low → high)
Descending-1 (high → low)
Top-N$sort then $limit
Pages$sort → $skip → $limit
IndexesBest when early ($match then $sort)

Live Preview

Sort published articles by views ascending or descending.

Published articles only. Simulates { $sort: { views: 1 | -1 } }.

Result
$sort: { views: -1 }

1. Node.js + MongoDB     15200
2. Intro to MongoDB      12400
3. REST API Design       11300
4. Aggregation Basics    8900
5. Express Middleware    7800
6. Indexing Strategies   6700
7. Schema Validation     5400

Worked Walkthrough — Highest Views First

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

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.

mongosh
db.articles.drop();
db.articles.insertMany([
  { title: "Intro to MongoDB",    category: "Database", views: 12400, published: true },
  { title: "Aggregation Basics",  category: "Database", views: 8900,  published: true },
  { title: "Node.js + MongoDB",   category: "Backend",  views: 15200, published: true },
  { title: "Indexing Strategies", category: "Database", views: 6700,  published: true },
  { title: "Draft: Sharding",     category: "Database", views: 0,     published: false },
  { title: "REST API Design",     category: "Backend",  views: 11300, published: true },
  { title: "Schema Validation",   category: "Database", views: 5400,  published: true },
  { title: "Express Middleware",  category: "Backend",  views: 7800,  published: true }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps eight documents in articles. Run find() to see them:

mongosh
db.articles.find({}, { title: 1, views: 1, published: 1, _id: 0 })

Read the important fields like this:

FieldExamplePlain English
views15200Primary sort key
publishedtrueFilter before sorting
title"REST API Design"What we show in results

How It Works

  1. Reset once. drop() keeps demos repeatable.
  2. Mixed publish state. One draft is excluded by later $match.
  3. find() shows insert order. $sort will change that next.

Example 2 — Sort by Views

Goal: published articles only, highest views first.

mongosh
db.articles.aggregate([
  { $match: { published: true } },
  { $sort: { views: -1 } },
  { $project: { title: 1, views: 1, _id: 0 } }
]);

How It Works

  1. Filter. $match drops the unpublished draft.
  2. Order. views: -1 puts the largest number first.
  3. Shape. $project keeps only title and views for a clean list.
  4. Ascending? Use views: 1 for low → high instead.

Example 3 — Sort + Limit (Top N)

Goal: top 3 by views, with title as a tie-breaker for stable order.

mongosh
db.articles.aggregate([
  { $match: { published: true } },
  { $sort: { views: -1, title: 1 } },
  { $limit: 3 },
  { $project: { title: 1, views: 1, _id: 0 } }
]);

How It Works

  1. Primary key. views: -1 ranks by popularity.
  2. Tie-breaker. If two articles share the same views, title: 1 decides order.
  3. Cap. $limit: 3 keeps only the head of the sorted list.
  4. Memory tip. Adjacent $sort + $limit can keep only top-N in memory.

Edge Cases & Pitfalls

Check these before shipping sorted lists with $sort.

ties

Equal values can reshuffle

Add a unique tie-breaker (_id or createdAt) so pages stay stable across requests.

memory

Large sorts need care

Prefer an index when $sort is early. For huge sets, filter first and consider adjacent $limit for top-N.

arrays

Array fields use min/max

Ascending sorts by the lowest array value; descending by the highest. Nested arrays are not flattened.

vs count

Not the same as $sortByCount

$sortByCount groups and ranks frequencies. Use $sort to order full documents.

Performance Notes

ApproachCostBest for
$match then indexed $sortOften avoids in-memory sortFiltered ordered lists
$sort + $limitTop-k friendlyLeaderboards / top-N
Late unindexed $sortIn-memory (or disk spill)After heavy reshaping stages

Put selective $match first when you can, index hot sort keys, and keep $sort next to $limit for top-N.

Key Takeaways

  • Role: reorder documents by field values.
  • Directions: 1 ascending, -1 descending.
  • Top-N / pages: sort first, then limit or skip.
  • Stability: add a unique tie-breaker field.

One line: $sort answers “put these documents in this field order.”

Frequently Asked Questions

$sort reorders documents in the aggregation pipeline by one or more fields. Use 1 for ascending (low→high, A→Z) and -1 for descending (high→low, Z→A).
{ $sort: { fieldName: 1 } } sorts ascending; { $sort: { fieldName: -1 } } sorts descending. Multi-field: { $sort: { score: -1, name: 1 } }.
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.

Next: $sortByCount

Group documents by a field and sort those groups by count.

$sortByCount tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful