Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 70 ยท CRUD: create and read

Projection: Choosing Fields

Learn MongoDB projection: include or exclude fields, handle _id, project nested fields, trim arrays with $slice and $elemMatch, and avoid mixing rules.

By default, find returns whole documents. That is wasteful when you only need a name and a price: the server reads the full document, sends every field over the network, and your application throws most of it away. A projection is the second argument to find (and findOne) that tells MongoDB which fields to return.

In this lesson you will include and exclude fields, deal with the special case of _id, reach into nested documents and arrays, and learn the one rule that causes most projection errors. If filters are new to you, read Finding Documents first.

The mongosh listings are real MongoDB commands and are read-only. The runnable examples use the JavaScript practice engine from The Practice Engine Used in This Tutorial, which implements inclusion, exclusion, dot paths, $slice and $elemMatch projections over an array of documents. It is a stand-in, not a database.

Two kinds of projection

Inclusion { name: 1 } returns only name (and _id).
Exclusion { notes: 0 } returns everything but notes.

Do not mix the two in one projection. The only exception is _id.

1 / 2

Including fields

Put 1 next to every field you want. This is an inclusion projection:

JavaScript
db.products.find({ category: "lighting" }, { name: 1, price: 1 })

Every returned document contains name, price and _id. Nothing else comes back, even if the stored document has twenty other fields. A document that does not have one of the requested fields simply omits it from the output; MongoDB does not invent a null.

Excluding fields

Put 0 next to the fields you do not want. This is an exclusion projection, and everything else is returned:

JavaScript
db.products.find({}, { description: 0, reviews: 0 })

Use exclusion when a document has one or two large fields you want to leave out, such as a long description or an embedded history. Use inclusion when you need a few fields from a big document.

The _id field

_id is returned in every projection unless you turn it off. That is why { name: 1 } gives you name and _id. To drop it, set it to 0 explicitly:

JavaScript
db.products.find({}, { _id: 0, name: 1, price: 1 })

This is the one exception to the no-mixing rule: you can exclude _id inside an inclusion projection.

The no-mixing rule

Apart from _id, one projection must be either all inclusions or all exclusions. This fails:

JavaScript
db.products.find({}, { name: 1, description: 0 })

The server answers with an error along the lines of Cannot do exclusion on field description in inclusion projection. The reason is that the two modes mean different things: "start from nothing and add these fields" versus "start from everything and remove these fields". Mixing them has no clear meaning. Decide which list is shorter and use that mode.

Nested fields

To project a field inside a nested document, use dot notation in quotes:

JavaScript
db.products.find({}, { name: 1, "stock.warehouse": 1 })

If stock is { warehouse: 40, store: 6 }, the result contains stock: { warehouse: 40 } and leaves out store. Dot paths also work with exclusion ({ "stock.store": 0 }) and through arrays of subdocuments: projecting "reviews.rating" returns the array with only the rating field of each review. Newer MongoDB versions also accept the nested form { stock: { warehouse: 1 } }; dot notation works everywhere and is the usual style.

JS Include, exclude and _id

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line demonstrates the rule: the engine raises the same kind of error as the server. Remove description: 0 to make it valid.

Projecting arrays

Arrays have two projection operators of their own.

$slice returns part of an array. A positive number gives the first elements, a negative number gives the last ones, and a two-element array [skip, count] skips some elements and then takes a number of them:

JavaScript
db.posts.find({}, { comments: { $slice: 3 } })      // first 3
db.posts.find({}, { comments: { $slice: -3 } })     // last 3
db.posts.find({}, { comments: { $slice: [2, 3] } }) // skip 2, take 3

$slice does not act as an inclusion or exclusion on its own. Used alone, it returns every other field of the document unchanged, and only trims the array. That makes it handy for showing "the last few comments" without loading a very long array.

$elemMatch returns only the first array element that matches a condition:

JavaScript
db.orders.find({}, { customer: 1, items: { $elemMatch: { sku: "A1" } } })

If no element matches, the array field is left out of that document. Be careful: it returns only one element even when several match. When you need all matching elements, use the aggregation operators from Working with Arrays in Pipelines. There is also a positional form, "items.$": 1, which returns the first element that matched the query filter. Both forms are limited, so for complex array reshaping reach for aggregation.

JS $slice and $elemMatch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three things in the output. A $slice projection on its own still returns customer, items and _id, because it trims one array and leaves the rest. The $elemMatch projection returns only the first of the two A1 items for Mia. And Omar's document has no A1 item, so his items field disappears.

When projection helps most

  • List pages. Show a name and a price, skip descriptions and long arrays.
  • APIs. Never send internal fields such as password hashes to a client: project them out at the query, in addition to filtering in your code.
  • Covered queries. If a query's filter and projection use only fields in one index, MongoDB can answer from the index without reading documents at all. The projection must leave out _id unless _id is in the index. Designing Compound Indexes shows this.

A projection does not change stored data. It only shapes what comes back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does db.users.find({}, { email: 1 }) return for each document?

    _id is included by default in an inclusion projection. Add _id: 0 to remove it.
  2. 2. Which projection is rejected by MongoDB?

    Inclusion and exclusion cannot be mixed, except for _id. The first option mixes them only through _id, which is allowed.
  3. 3. Which projection returns the last three elements of the comments array?

    A negative $slice counts from the end of the array. A positive number takes elements from the start.
  4. 4. An $elemMatch projection on an array matches three elements. How many are returned?

    The $elemMatch projection returns only the first matching element. Use aggregation operators such as $filter to return all matches.

Summary

  • A projection is the second argument to find/findOne and limits the fields returned; it never changes stored data.
  • Use 1 to include fields or 0 to exclude them; do not mix the two, except that _id: 0 is allowed in an inclusion projection.
  • _id is returned unless you set it to 0.
  • Dot notation projects nested fields, including fields of subdocuments inside arrays.
  • $slice trims arrays (first n, last n, or skip and take) and keeps the other fields; $elemMatch returns only the first matching element.
  • Projections reduce network and memory use and can make covered queries possible.

Next, put the results in order with Sorting, Limiting and Skipping.