Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

Ask "Is my list of wanted fields shorter than my list of unwanted ones?" Shorter wanted list → inclusion. Shorter unwanted list → exclusion. Then decide about _id.

Title plus The Hobbit's first ratingStep 1 of 4
  1. Pick the style

    Wanted: title and one rating. That list is short, so use inclusion.

The trap: expecting { title: 1 } to return only the title. _id always tags along unless you switch it off.

Drills

Answer fast — trust the rule.

quick drill

What does db.books.find({ _id: 5 }, { title: 1 }) return?

quick drill

Which projection is an error?

quick drill

What does { ratings: { $slice: -1 } } keep for Dune?

quick drill

What does { ratings: { $slice: [1, 1] } } keep for The Hobbit?

Remember

  • List what you want with 1, or what you don't with 0; never both, except _id.
  • Shortcut: shorter wanted list means inclusion; then decide about _id.
  • Trap: _id comes back unless you set _id: 0, and $slice counts from the end when negative.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainA lightweight book list

The mobile app's list screen needs, for every book, only the title, the price and the most recent rating (the last element of ratings), with no _id. Write the find call, show what it returns for The Hobbit, and explain the rule about mixing 1s and 0s.