← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 4 of 7

Projection

Projection chooses which fields come back so you transfer only what you need.

In this page:

  1. Projection
Syntax
javascript
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

bash
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
  1. Mixing include and exclude
  2. Forgetting _id is returned by default
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.