Working with Projection

1. Including Fields

FormEffect
{name: 1, email: 1}Include + _id by default
{name: 1, _id: 0}Exclude _id explicitly
RuleCannot mix include/exclude (except _id)

2. Excluding Fields

FormEffect
{password: 0}Exclude; everything else included
{password: 0, "internal.secret": 0}Nested exclusion

3. Projecting Array Elements

OperatorEffect
$slice: nFirst n (or last if negative)
$slice: [skip, limit]Window
$elemMatchFirst element matching condition
$First element matching query filter
db.posts.find({}, { comments: { $slice: -3 } });  // last 3 comments

4. Using $elemMatch in Projection

AspectDetail
ReturnsFirst array element matching condition
Differs from $Condition specified in projection (not query)
db.classes.find({}, { students: { $elemMatch: { grade: { $gte: 90 } } } });

5. Projecting Positional Elements ($)

AspectDetail
Syntax{ "items.$": 1 }
ReturnsOnly the first matching element from query filter
LimitationOnly one positional projection per query

6. Excluding _id Field

FormEffect
{_id: 0, name: 1}Only valid mix of include/exclude
Use caseCleaner export, joining external systems

7. Using $meta for Text Search Scores

FieldReturns
{$meta: "textScore"}Relevance score (requires $text query)
{$meta: "indexKey"}Index key used (debugging)
{$meta: "searchScore"}Atlas Search score
{$meta: "searchHighlights"}Atlas Search highlights

8. Projecting Nested Fields

FormEffect
{"profile.city": 1}Dot notation include
{profile: {city: 1}}Nested object form
AggregationUse $project with expressions for renaming

9. Understanding Projection Limitations

LimitationDetail
No mix include/excludeExcept _id
One $ per queryMultiple positional updates need filtered ($[id])
Field renamingNot in find(); use aggregation $project
Computed fieldsAggregation only (find supports limited 4.4+ expressions)

10. Using Projection for Performance

BenefitHow
Network bytes ↓Exclude large fields (images, blobs)
Covered queryAll projected fields in index → no doc fetch
CPU ↓Less BSON serialization
Memory ↓Smaller client-side objects
Note: A covered query requires projection that includes ONLY indexed fields and excludes _id (unless _id is part of the index).