Skip to main content

πŸ‘ $project

Including fields in a projection​

A document from the books collection looks like:

{
_id: '0395623650',
title: 'Platero y yo / Platero and I (Spanish-English Bilingual Edition) (English and Spanish Edition)',
authors: [
{
_id: '64cc2db4830ba29148db5180',
name: 'Juan RamΓ³n JimΓ©nez'
}
],
pages: 64,
year: 1994,
synopsis: 'Selections from a classic of world literature present a picture of life in the town of Moguer, in Andalusia, Spain.\n' +
'\n' +
'\n' +
' Presents a picture of life in the town of Moguer, in Andalusia, Spain, as seen through the eyes of a wandering poet and his faithful donkey.\n',
cover: 'https://images.isbndb.com/covers/36/57/9780395623657.jpg',
attributes: [
{
key: 'edition',
value: 'F First Edition Thus'
},
{
key: 'dimensions',
value: 'Height: 10.499979 Inches, Length: 6.999986 Inches, Weight: 2.0502990366 Pounds, Width: 0.12499975 Inches'
},
{
key: 'isbn13',
value: '9780395623657'
},
{
key: 'msrp',
value: 1.99
},
{
key: 'isbn',
value: '0395623650'
},
{
key: 'isbn10',
value: '0395623650'
}
],
totalInventory: 1,
available: 1,
binding: 'Hardcover',
language: 'en',
longTitle: 'Platero y yo / Platero and I (Spanish-English Bilingual Edition) (English and Spanish Edition)',
publisher: 'Clarion Books'
}

If we're interested in the titles, we can use $project to select just the fields we're interested in. As an example, to get just the book's title and year, we'll write:

[
{
$project: { title: 1, year: 1 }
}
]
  • 1 means "show that field.". Once you started an inclusion projection you can't exclude other fields (you just keep adding the fields you want to see)
  • 0 means "hide that field.". Once you started an exclusion projection you can't include other fields (you just keep adding the fields you don't want to see)
  • The primary key _id field is shown by default.

So we can exclude fields and show all fields except attributes using:

[
{
$project: { attributes: 0 }
}
]

πŸ‘ Show only title and cover.

Answer
[
{
$project: { title: 1, cover: 1 }
}
]

Excluding fields​

πŸ‘ Exclude the cover, attributes, and _id fields from the result.

Answer
[
{
$project: {_id: 0, attributes: 0, cover: 0}
}
]

Including and excluding fields​

danger

You can't include and exclude fields in the same projection. If you start including, you must keep including, and vice versa.

For instance, this will fail:

db.books.aggregate([{$project: {title: 1, attributes: 0}}])

MongoServerError: Invalid $project :: caused by :: Cannot do exclusion on field attributes in inclusion projection
info

The only exception to this rule is the _id field, which we can exclude in an inclusion projection.

db.books.aggregate([{$project: {title: 1, _id: 0}}])