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.