OPTIONS
翻译或纠错本页面

$elemMatch (query)

Definition

$elemMatch

The $elemMatch operator matches documents in a collection that contain an array field with at least one element that matches all the specified query criteria.

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

Behavior

You cannot specify a $where expression as a query criterion for $elemMatch.

Examples

Element Match

Given the following documents in the scores collection:

{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }

The following query matches only those documents where the results array contains at least one element that is both greater than or equal to 80 and is less than 85.

db.scores.find(
   { results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)

The query returns the following document since the element 82 is both greater than or equal to 80 and is less than 85

{ "_id" : 1, "results" : [ 82, 85, 88 ] }

For more information on specifying multiple criterion on array elements, see 为数组元素指定复合条件.

Array of Embedded Documents

Given the following documents in the survey collection:

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

The following query matches only those documents where the results array contains at least one element with both product equal to "xyz" and score greater than or equal to 8.

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

Specifically, the query matches the following document:

{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }

For more information on querying arrays, see 数组, including 为数组元素指定复合条件 and 内嵌文档数组 sections.

←   $all $size  →