The $ and $elemMatch Array Projections
Learners will return only the first matching array element or a filtered sub-array using $ and $elemMatch projections.
The Problem: Returning Only One Array Element
Sometimes a query matches a document based on an array element—for example, finding an order that contains a specific product—but you only want the matching array element returned, not the entire array. The standard inclusion projection returns all elements of the array. MongoDB provides two special array projection operators to solve this: the positional $ operator and $elemMatch.
The $ Positional Operator
The $ positional projection operator returns the first element of an array that matches the query condition. It is placed in the projection where the array field name normally goes. The condition that matched in the filter is automatically used to determine which element to project. Only one $ can appear in a single projection.
// Find the order and return only the matching line item
db.orders.findOne(
{ 'items.productId': ObjectId('p1') },
{ projection: { 'items.$': 1 } }
);
// Result: { _id: ..., items: [{ productId: ObjectId('p1'), qty: 2, price: 9.99 }] }
// Only the FIRST matching element is returnedAll lessons in this course
- Inclusion vs Exclusion Projections
- Projecting Nested and Array Fields
- The $ and $elemMatch Array Projections
- Projection Best Practices for API Responses