Projection
Projection chooses which fields come back so you transfer only what you need.
In this page:
Syntax
db.collection_name.find(filter, { field1: 1, field2: 1, _id: 0 })
Projection
The second argument to find lists fields with 1 to include or 0 to exclude. You cannot mix inclusion and exclusion except for _id, which is included by default unless set to 0. Dotted paths project nested fields, and $slice trims arrays.
Note:
Always exclude _id explicitly when you do not want it.
Example: Projection
test> db.users.insertOne({ _id: 1, name: "Ada", age: 36, address: { city: "London", zip: "N1" }, skills: ["a", "b", "c"] })
{ acknowledged: true, insertedId: 1 }
test> db.users.find({}, { name: 1 })
[ { _id: 1, name: 'Ada' } ]
test> db.users.find({}, { name: 1, _id: 0, "address.city": 1 })
[ { name: 'Ada', address: { city: 'London' } } ]
test> db.users.find({}, { age: 0, address: 0 })
[ { _id: 1, name: 'Ada', skills: [ 'a', 'b', 'c' ] } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Mixing include and exclude
- Forgetting _id is returned by default
- Fetching whole documents when two fields are enough
Chapter Summary
- 1 includes and 0 excludes
- Do not mix except _id
- _id is included by default
- Dotted paths project nested fields
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: