Stop 05 · MongoDB FundamentalsTopics · 7/9

Projection, Sort and Limit

Part of the MERN Stack Roadmap

In short

A product document might have 30 fields, but your list page needs four. Projection, sort and limit trim the response so your API sends less data and your app feels fast on a 4G connection.

Projection returns only the fields you need, sort orders results and skip and limit return one page at a time. Together they keep API responses small and fast.

The jaadu sips chai and snips just the top strips off a stack of newspapers with scissors, lining up the ten best pieces on the table.

Think of it like this

Reading the newspaper headlines

You don't read the whole newspaper every morning. You read only the headline and first line (projection), front page first (sort), and stop after the top ten stories (limit). Same paper, far less effort.

Watch it happen

find(filter, projection).sort().skip().limit()

Filter
Sort
Skip
Limit
Projection

1/5Match products in the kitchen category: 240 documents.

The big ideas

What you need to know

Projection

{ name: 1, price: 1 } includes fields. { description: 0 } excludes them. Don't mix the two, except for _id: 0.

Sort

{ price: 1 } is ascending, { price: -1 } descending. Add a second key like _id to break ties.

Limit and skip

limit caps the number of results. skip jumps over some, which is how page-based pagination works.

Big skips get slow

skip still walks past skipped documents. For very deep pages, use range-based paging such as _id > lastSeenId.

See it in code

Walk through the code

js
1db.products2  .find(3    { category: "kitchen" },4    { name: 1, price: 1, _id: 0 }5  )6  .sort({ price: 1, name: 1 })7  .skip(20)8  .limit(10);9 10// Top 5 most expensive products, just name and price11db.products.find({}, { name: 1, price: 1 }).sort({ price: -1 }).limit(5);

1/5The first argument is the filter.

Page 3 of kitchen products, cheapest first, returning only two fields.

Save yourself the pain

Common mistakes

Oops

{ name: 1, description: 0 } in the same projection.

Do this instead

Use either inclusion or exclusion. The only exception is _id, which you can exclude in an inclusion projection.

Oops

Limiting before deciding on a sort and expecting "the newest ten".

Do this instead

Without sort, MongoDB returns documents in no guaranteed order. Always sort when order matters.

Your mission

Shape a product list

~20 min

Quick check

You write .limit(5).sort({ price: -1 }). What do you get?

Go deeper

  1. 1Return only name and price for a product list using a projection.
  2. 2Sort by price descending and then by name.
  3. 3Build page 3 of results with skip and limit and note why large skips get slow.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge