On this page
$elemMatch (projection)
See also
在本页面
Definition
$elemMatch
- $elemMatch运算符将查询结果中
<array>
字段的内容限制为仅包含与$elemMatch条件匹配的 first 元素。
- $elemMatch运算符将查询结果中
Usage Considerations
$运算符和$elemMatch运算符都基于条件从数组投影 first 匹配元素。
$运算符根据查询语句中的某些条件从集合中的每个文档中投影第一个匹配的数组元素。
$elemMatch投影运算符采用显式条件参数。这使您可以根据查询中没有的条件进行投影,或者如果需要基于阵列的嵌入式文档中的多个字段进行投影。有关示例,请参见数组字段限制。
views上的db.collection.find()个操作不支持$elemMatch个投影运算符。
- 您不能在$elemMatch中指定$text查询表达式。
Examples
$elemMatch投影运算符上的示例假定包含以下文档的school
集合:
{
_id: 1,
zipcode: "63109",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: "63110",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: 102, age: 7 },
{ name: "ruth", school: 102, age: 16 },
]
}
Zipcode Search
以下find()操作查询zipcode
字段的值为63109
的所有文档。 $elemMatch投影仅返回students
数组的 first 匹配元素,其中school
字段的值为102
:
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102 } } } )
该操作返回以下文档:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
对于
_id
等于1
的文档,students
数组包含多个元素,school
字段等于102
。但是,$elemMatch投影仅返回数组中的第一个匹配元素。_id
等于3
的文档在结果中不包含students
字段,因为其students
数组中没有元素与$elemMatch条件匹配。
$ elemMatch 与多个字段
$elemMatch投影可以在多个字段上指定条件:
以下find()操作查询zipcode
字段的值为63109
的所有文档。投影包括students
数组的 first 匹配元素,其中school
字段的值为102
并且 age
字段的值大于10
:
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )
该操作返回zipcode
等于63109
的三个文档:
{ "_id" : 1, "students" : [ { "name" : "jess", "school" : 102, "age" : 11 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "ruth", "school" : 102, "age" : 16 } ] }
_id
等于3
的文档不包含students
字段,因为没有数组元素与$elemMatch条件匹配。
See also
$ (projection) operator