On this page
$elemMatch (query)
在本页面
See also
Definition
$elemMatch
- $elemMatch运算符匹配包含一个包含至少一个与所有指定查询条件匹配的元素的数组字段的文档。
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
如果在$elemMatch表达式中仅指定一个<query>
条件,则无需使用$elemMatch。
Behavior
您不能在$elemMatch中指定$where表达式。
您不能在$elemMatch中指定$text查询表达式。
Examples
Element Match
鉴于scores
集合中的以下文档:
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
以下查询仅匹配results
数组包含至少一个大于或等于80
且小于85
的元素的那些文档。
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
该查询返回以下文档,因为元素82
都大于或等于80
并且小于85
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
有关在数组元素上指定多个条件的更多信息,请参见为数组元素指定多个条件。
嵌入式文档数组
鉴于survey
集合中的以下文档:
{ _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 } ] }
以下查询仅与results
数组包含至少一个元素同时product
等于"xyz"
和score
都大于或等于8
的那些文档匹配。
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)
具体而言,查询与以下文档匹配:
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }
单查询条件
如果您在$elemMatch表达式中指定单个查询谓词,则$elemMatch是不必要的。
例如,考虑以下示例,其中$elemMatch仅指定单个查询谓词{ product: "xyz" }
:
db.survey.find(
{ results: { $elemMatch: { product: "xyz" } } }
)
由于$elemMatch仅指定一个条件,因此$elemMatch表达式不是必需的,而是可以使用以下查询:
db.survey.find(
{ "results.product": "xyz" }
)
Additional Examples
有关查询数组的其他示例,请参见:
有关查询的其他示例,请参见:
See also