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: 0is the one allowed exception. $slicetrims an array:{ ratings: { $slice: 1 } }keeps the first element,-1the 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.
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.
What does db.books.find({ _id: 5 }, { title: 1 }) return?
Which projection is an error?
What does { ratings: { $slice: -1 } } keep for Dune?
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:
_idcomes back unless you set_id: 0, and$slicecounts from the end when negative.
