Chapter 70: Node.js MongoDB Sort

MongoDB when using Node.js with Mongoose.

We will go through everything step by step, slowly and carefully — exactly as if I am sitting next to you right now:

  • I open VS Code
  • I open the terminal
  • We type every line together
  • We run the code
  • We look at the results in the console and in MongoDB Compass
  • I explain why we write each line this way
  • I show what most beginners do wrong (and why it causes confusion or bugs)
  • I show what intermediate developers often forget (leads to wrong order or slow queries)
  • I show what real production code looks like in serious Node.js backends in 2025–2026

Goal of this lesson

Master sorting in MongoDB queries so that:

  • Your API always returns data in the expected order
  • Sorting is fast (uses indexes)
  • Sorting is safe (no injection risk)
  • Sorting is flexible (user-controlled sort field & direction)
  • You understand when and why to sort in memory vs in the database

Step 1 – Project setup (minimal but realistic)

If you don’t have a project yet:

Bash

tsconfig.json

JSON

package.json scripts

JSON

.env.example

text

Step 2 – MongoDB connection (safe & modern)

src/config/mongodb.ts

TypeScript

src/config/env.ts

TypeScript

Step 3 – Realistic Mongoose model (Task) with indexes

src/models/task.model.ts

TypeScript

Why these indexes?

  • { createdAt: -1 } → very fast when sorting newest first
  • { priority: 1, dueDate: 1 } → fast when sorting by priority then due date
  • Text index → fast full-text search on title

Step 4 – Seed some test data (run once)

src/seed.ts

TypeScript

Run once:

Bash

Now we have 5 tasks with different priorities, due dates, completion status, and points.

Step 5 – Basic sorting examples

5.1 Sort by createdAt – newest first

TypeScript

Result order Tasks appear from most recently created → oldest

5.2 Sort by priority (custom order: high → medium → low)

TypeScript

Problem: MongoDB sorts strings alphabetically → ‘high’ < ‘low’ < ‘medium’

Solution: use FIELD() or CASE logic via aggregation (or map in JS)

Better – custom priority sort

TypeScript

Best production way: use aggregation with $addFields

TypeScript

Step 6 – Dynamic sorting (user-controlled – safe version)

src/controllers/task.controller.ts

TypeScript

Safe URLs

  • /api/tasks/sorted?sortBy=priority&sortOrder=asc
  • /api/tasks/sorted?sortBy=title&sortOrder=desc

Security note

Never do:

TypeScript

Always whitelist allowed sort fields.

Step 7 – Summary – MongoDB sorting best practices in Node.js 2025–2026

Best Practice Why it matters Code pattern example
Always use .sort() MongoDB does NOT guarantee order without it .sort({ createdAt: -1 })
Use .lean() for read-only lists 2–5× faster – returns plain JS objects .find().lean().sort({ … })
Use indexes on sorted fields 10×–100× faster schema.index({ createdAt: -1 })
Whitelist dynamic sort fields Prevents injection in .sort() if (allowedFields.includes(sortBy))
Use aggregation for custom sorting When simple .sort() is not enough (e.g. priority order) $addFields + $sort
Combine sort + limit + skip Essential for paginated lists .sort(…).skip(offset).limit(pageSize)
Prefer cursor-based pagination Avoid slow skip on large offsets { _id: { $gt: lastId } }
Add text index for search + sort by relevance Fast full-text + best-match-first schema.index({ title: ‘text’ }) + $text + $meta: “textScore”

Which direction would you like to go much deeper into next?

  • Login + JWT authentication with MongoDB
  • Full task CRUD (create/read/update/delete + ownership check)
  • Advanced pagination (cursor-based, infinite scroll)
  • Text search + relevance sorting
  • Aggregation pipeline examples (group, match, unwind, etc.)
  • Performance tuning (indexes, explain(), profiling)

Just tell me what you want to build or understand next — I’ll continue with complete, secure, production-ready code and explanations. 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *