TExcelTAD
Home › MongoDB › MongoDB Projection

MongoDB Projection

By default find() returns whole documents. A projection, the second argument of find() and findOne(), chooses which fields come back. Returning less data means less network traffic and less memory in your application, which matters once documents get large.

Including fields

Set a field to 1 (or true) to include it. Only the listed fields are returned, plus _id, which is included unless you say otherwise:

mongosh · try it yourself
print(db.products.find({ category: 'snacks' }, { name: 1, price: 1 }).toArray());
[
  { _id: 16, name: 'Almond Biscotti', price: 7.5 },
  { _id: 17, name: 'Dark Chocolate Bar', price: 4.5 },
  { _id: 18, name: 'Oat Cookies', price: 5 },
  { _id: 19, name: 'Salted Pretzels', price: 3.5 }
]

Excluding _id

_id is the one field you may exclude inside an inclusion projection:

mongosh · try it yourself
print(db.products.find({ category: 'snacks' }, { _id: 0, name: 1, price: 1 }).toArray());
[
  { name: 'Almond Biscotti', price: 7.5 },
  { name: 'Dark Chocolate Bar', price: 4.5 },
  { name: 'Oat Cookies', price: 5 },
  { name: 'Salted Pretzels', price: 3.5 }
]

Excluding fields

Set fields to 0 to return everything except them:

mongosh · try it yourself
print(db.customers.findOne({ _id: 2 }, { joined: 0, interests: 0 }));
{
  _id: 2,
  name: 'Alan Turing',
  email: 'alan@example.com',
  tier: 'silver',
  address: { city: 'Manchester', country: 'UK' }
}

Warning: You can't mix inclusion and exclusion in one projection (except for _id). { name: 1, price: 0 } throws Cannot do exclusion on field price in inclusion projection.

mongosh · try it yourself
try {
  db.products.find({}, { name: 1, price: 0 }).toArray();
} catch (err) {
  print(err.message);
}
Cannot do exclusion on field price in inclusion projection

Projecting nested fields

Dot notation works in projections too. The result keeps the nesting:

mongosh · try it yourself
print(db.customers.find({ tier: 'gold' }, { _id: 0, name: 1, 'address.city': 1 }).toArray());
[
  { name: 'Ada Lovelace', address: { city: 'London' } },
  { name: 'Grace Hopper', address: { city: 'New York' } },
  { name: 'Barbara Liskov', address: { city: 'Boston' } }
]

For arrays of embedded documents, a dotted path keeps that field in every element:

mongosh · try it yourself
print(db.orders.findOne({ _id: 1005 }, { 'items.name': 1, 'items.qty': 1 }));
{
  _id: 1005,
  items: [
    { name: 'Pour-Over Dripper', qty: 1 },
    { name: 'Paper Filters (100)', qty: 2 },
    { name: 'House Blend', qty: 1 }
  ]
}

Array projection operators

Operator Returns
{ field: { $slice: n } } the first n elements (negative n: the last ones)
{ field: { $slice: [skip, n] } } n elements after skipping skip
{ field: { $elemMatch: {…} } } only the first element that matches the condition
{ 'field.
#39;: 1 }
the first element that matched the query filter
mongosh · try it yourself
print(db.products.findOne({ _id: 3 }, { name: 1, tags: { $slice: 1 } }));
print(db.orders.findOne({ _id: 1005 }, { items: { $elemMatch: { price: { $lt: 10 } } } }));
print(db.orders.findOne({ 'items.productId': 2 }, { 'items.
  

: 1 }));
{ _id: 3, name: 'Ethiopia Yirgacheffe', tags: [ 'light' ] }
{
  _id: 1005,
  items: [ { productId: 15, name: 'Paper Filters (100)', qty: 2, price: 6 } ]
}
{
  _id: 1005,
  items: [ { productId: 2, name: 'House Blend', qty: 1, price: 18 } ]
}

Computed fields

Since MongoDB 4.4 a projection may also contain expressions, just like the $project aggregation stage. Expressions refer to existing fields with '$fieldName':

mongosh · try it yourself
db.products.find({ category: 'equipment' }, {
  _id: 0,
  name: 1,
  label: { $toUpper: '$name' },
  inStock: { $gt: ['$stock', 0] }
}).limit(3).forEach(p => print(p));
{
  name: 'Pour-Over Dripper',
  label: 'POUR-OVER DRIPPER',
  inStock: true
}
{ name: 'French Press', label: 'FRENCH PRESS', inStock: true }
{ name: 'Burr Grinder', label: 'BURR GRINDER', inStock: true }

Test yourself

What does find({}, { name: 1 }) return for each document?

  1. Only name
  2. name and _id
  3. Everything except name
  4. An error

Which projection is invalid?

  1. { _id: 0, name: 1 }
  2. { price: 0, stock: 0 }
  3. { name: 1, price: 0 }
  4. { 'address.city': 1 }

How do you return only the last two elements of tags?

  1. { tags: { $slice: 2 } }
  2. { tags: { $slice: -2 } }
  3. { tags: -2 }
  4. { 'tags. : 2 }