Skip to the workspace
Pebellslearn by building
Query Operators  ›  Capstone Project

Projection: Including, Excluding and $slice

$project 15 minA projection, the second argument to find, returns only the fields you include or everything except the fields you exclude, never mixing the two except for _id, and $slice returns part of an array.

mongodb / Projection: Including, Excluding and $slice

Explore each scene at your own pace.

01 · The rule

The rule

Projection: Including, Excluding and $slice

A phone list screen shows only titles and prices, yet each book document also carries a publisher, genres and every rating ever given. Sending all of it wastes bandwidth and memory. A projection, the second argument to find, trims each result to what the screen needs.

The rule

List what you want with 1, or what you don't with 0; never both, except _id.

db.books.find({ _id: 3 }, { title: 1, year: 1 })
// { _id: 3, title: "Emma", year: 1815 }

db.books.find({ _id: 3 }, { _id: 0, title: 1 })
// { title: "Emma" }

db.books.find({ _id: 3 }, { ratings: 0, publisher: 0 })
// every field except ratings and publisher

db.books.find({ _id: 1 }, { "publisher.name": 1 })
// { _id: 1, publisher: { name: "Chilton" } }
  • Inclusion (1s): only the listed fields come back, plus _id, which is included unless you set _id: 0.
  • Exclusion (0s): everything comes back except the listed fields.
  • Mixing 1s and 0s, as in { title: 1, price: 0 }, is an error. _id: 0 is the one allowed exception.
  • $slice trims an array: { ratings: { $slice: 1 } } keeps the first element, -1 the last, [1, 2] skips 1 then keeps 2.

The same 1-and-0 shape reappears as the $project stage when you later build aggregation pipelines.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.