What is Projection?
Projection in MongoDB controls which fields are returned in query results. By default, find() returns all fields in matching documents. Using a projection document as the second argument, you can include only the fields you need or exclude fields you do not want -- reducing network transfer and improving performance.
Inclusion Projection
Set fields to 1 to include only those fields. The _id field is always included unless explicitly excluded:
// Return only name and email
db.users.find(
{ status: "active" },
{ name: 1, email: 1 }
)
// Result: { _id: ..., name: "Alice", email: "alice@example.com" }
// Exclude _id from the results
db.users.find(
{ status: "active" },
{ name: 1, email: 1, _id: 0 }
)
// Result: { name: "Alice", email: "alice@example.com" }Exclusion Projection
Set fields to 0 to exclude them and return everything else:
// Return all fields except password and internalNotes
db.users.find(
{},
{ password: 0, internalNotes: 0 }
)You cannot mix inclusion and exclusion in the same projection, except for explicitly excluding _id alongside inclusions.
Projecting Nested Fields
Use dot notation to project specific fields from embedded documents:
// Return only the city from the address subdocument
db.users.find(
{},
{ name: 1, "address.city": 1, "address.state": 1 }
)
// Result: { _id: ..., name: "Alice", address: { city: "SF", state: "CA" } }Array Projection Operators
MongoDB offers special operators for projecting array elements:
// $slice - Return first N array elements
db.articles.find(
{},
{ title: 1, comments: { $slice: 5 } }
)
// $slice - Return last 3 elements
db.articles.find(
{},
{ title: 1, comments: { $slice: -3 } }
)
// $slice with skip: skip 10, return next 5
db.articles.find(
{},
{ title: 1, comments: { $slice: [10, 5] } }
)
// $elemMatch in projection - Return first matching array element
db.students.find(
{ _id: studentId },
{ scores: { $elemMatch: { subject: "math" } } }
)Projection in Aggregation
The $project stage in the aggregation pipeline offers more power, including computed fields:
db.users.aggregate([
{
$project: {
_id: 0,
fullName: { $concat: ["$firstName", " ", "$lastName"] },
email: 1,
isAdmin: { $eq: ["$role", "admin"] }
}
}
])Key Takeaways
- Use inclusion (
1) or exclusion (0) projections -- do not mix them (except_id: 0). - Dot notation works for projecting nested document fields.
$sliceand$elemMatchcontrol which array elements are returned.- Use
$projectin aggregation pipelines for computed fields.
Try this query in UnifySQL
Write, optimize, and collaborate on MongoDB queries with AI assistance.
Start Free