$elemMatch

Projects only the first element from an array that matches the specified query condition, useful for returning specific array elements.

Syntax

{ <field>: { $elemMatch: { <query_conditions> } } }

Parameters

fieldstringrequired

Array field name to project elements from

query_conditionsobjectrequired

Query conditions to match array elements

Examples

Project matching array element

Return only the first array element that matches criteria

Query:

db.students.find({}, { name: 1, grades: { $elemMatch: { subject: "Math", score: { $gte: 85 } } } })

Output:

Students with name and only the first Math grade >= 85 from grades array

Filter nested array objects

Project specific objects from nested array based on conditions

Query:

db.orders.find({}, { orderId: 1, items: { $elemMatch: { category: "electronics", price: { $gt: 100 } } } })

Output:

Orders with orderId and first electronics item over $100 from items array

Related