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:
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:
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:
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.
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:
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:
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 |
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.