Choosing Fields with Projections
A projection, the second argument to find, chooses which fields come back; 1 includes a field and 0 leaves it out, _id comes along unless you leave it out, and the two can't be mixed except for _id.
Apprentice · MongoDB · Updated
After this lesson you can
- Choose which fields find gives back with a projection that includes or excludes fields, _id included
- Predict what a projection gives back for a nested field, and spot one that mixes including and excluding
Key takeaways
- A projection is the second pair of braces in find or findOne. It changes which fields come back, never which documents match.
- A field set to 1 is included. The _id comes along too, unless the projection sets it to 0.
- A field set to 0 is left out, and every other field comes back.
- A projection can't include some fields and exclude others. The one field it may set either way is _id.
- Dot notation picks a field inside an embedded document, or a field of every item in an array of documents.
A recipe list on a phone shows each recipe's name and cooking time, not its twenty fields. A store's search page shows a product's name and price, not its whole warehouse record. Asking the database for only the fields a screen needs keeps answers short to read and quick to send, and you'll do it on almost every list page you build.
The examples use Sunday Kitchen's 40 recipes from Fields Inside Fields: Dot Notation. The lessons so far, in this chapter and the one before, have used a second pair of braces such as { name: 1, minutes: 1 } to keep answers short. This lesson explains it.
A whole recipe is a lot to read
Each card now carries its nutrition and ingredients, so one recipe fills the screen:
db.recipes.findOne({ name: "Tiramisu" })
{
_id: 17,
name: 'Tiramisu',
cuisine: 'Italian',
meal: 'dessert',
minutes: 30,
servings: 8,
vegetarian: true,
rating: 4.7,
tags: [ 'sweet', 'make-ahead' ],
nutrition: { calories: 410, protein: 8 },
ingredients: [
{ name: 'ladyfingers', amount: 24, unit: 'whole' },
{ name: 'mascarpone', amount: 16, unit: 'oz' },
{ name: 'eggs', amount: 4, unit: 'whole' },
{ name: 'coffee', amount: 1, unit: 'cups' }
]
}
Sunday Kitchen's dessert page needs two of those fields. Sending all of them for every recipe, to throw most away, wastes the reader's time and the network's.
Include fields with 1
Think of a stencil laid over a page: only the words under the holes show through. A projection is that stencil, written as the second argument to find or findOne. Set a field to 1, read "show", and it's included:
db.recipes.find({ meal: "dessert" }, { name: 1, minutes: 1 })
[
{ _id: 3, name: 'Lemon Bars', minutes: 50 },
{ _id: 17, name: 'Tiramisu', minutes: 30 },
{ _id: 23, name: 'Chocolate Chip Cookies', minutes: 30 },
{ _id: 28, name: 'Mango Sticky Rice', minutes: 40 },
{ _id: 31, name: 'Apple Crumble', minutes: 55 },
{ _id: 39, name: 'Churros', minutes: 45 }
]
Read it aloud as "find the desserts, and show their name and minutes". The filter still decides which recipes match; the projection decides only what you see of each one. The _id came along without being asked: it always does, unless you set it to 0:
db.recipes.find({ meal: "dessert" }, { name: 1, minutes: 1, _id: 0 })
[
{ name: 'Lemon Bars', minutes: 50 },
{ name: 'Tiramisu', minutes: 30 },
{ name: 'Chocolate Chip Cookies', minutes: 30 },
{ name: 'Mango Sticky Rice', minutes: 40 },
{ name: 'Apple Crumble', minutes: 55 },
{ name: 'Churros', minutes: 45 }
]

Exclude fields with 0, but don't mix
Sometimes it's shorter to say what to leave out. Set a field to 0, read "hide", and every other field comes back:
db.recipes.findOne({ _id: 17 }, { ingredients: 0, tags: 0 })
{
_id: 17,
name: 'Tiramisu',
cuisine: 'Italian',
meal: 'dessert',
minutes: 30,
servings: 8,
vegetarian: true,
rating: 4.7,
nutrition: { calories: 410, protein: 8 }
}
A projection is one or the other: a list of fields to show, or a list of fields to hide. Mix them, and the server refuses:
db.recipes.find({ meal: "dessert" }, { name: 1, tags: 0 })
Uncaught MongoServerError[Location31254]: Cannot do exclusion on field tags in inclusion projection
The error says "Cannot do exclusion on field tags in inclusion projection": the 1 made it a list of fields to show, so a 0 has no meaning there. Everything not listed is hidden already, so the fix is to drop tags: 0. The one exception is _id, which may be 0 in a list of fields to show, as above.
A field inside a field
Dot notation from Fields Inside Fields: Dot Notation works in a projection too. The dessert page wants each dessert's calories, and nothing else of its nutrition:
db.recipes.find({ meal: "dessert" }, { name: 1, "nutrition.calories": 1, _id: 0 })
[
{ name: 'Lemon Bars', nutrition: { calories: 210 } },
{ name: 'Tiramisu', nutrition: { calories: 410 } },
{ name: 'Chocolate Chip Cookies', nutrition: { calories: 180 } },
{ name: 'Mango Sticky Rice', nutrition: { calories: 450 } },
{ name: 'Apple Crumble', nutrition: { calories: 340 } },
{ name: 'Churros', nutrition: { calories: 260 } }
]
Notice the shape: the calories come back inside nutrition, where they live, not as a field of their own. On an array of documents, a dotted projection keeps that one field of every item. Hummus's shopping list, names only:
db.recipes.findOne({ _id: 35 }, { name: 1, "ingredients.name": 1 })
{
_id: 35,
name: 'Hummus',
ingredients: [
{ name: 'chickpeas' },
{ name: 'tahini' },
{ name: 'lemon' },
{ name: 'garlic' }
]
}
| You want | The projection |
|---|---|
Only some fields, and the _id |
{ name: 1, minutes: 1 } |
Only some fields, without the _id |
{ name: 1, minutes: 1, _id: 0 } |
| Every field but a few | { ingredients: 0, tags: 0 } |
| One field inside an embedded document | { "nutrition.calories": 1 } |
| One field of every item in a list | { "ingredients.name": 1 } |
Check yourself
2 questions to try on the lesson page.
So what
Every list page shows a few fields of many documents. A projection asks for exactly those, so answers stay short and screens get only what they show.