$elemMatch (projection)

在本页面

Definition

Usage Considerations

$运算符和$elemMatch运算符都基于条件从数组投影 first 匹配元素。

$运算符根据查询语句中的某些条件从集合中的每个文档中投影第一个匹配的数组元素。

$elemMatch投影运算符采用显式条件参数。这使您可以根据查询中没有的条件进行投影,或者如果需要基于阵列的嵌入式文档中的多个字段进行投影。有关示例,请参见数组字段限制

views上的db.collection.find()个操作不支持$elemMatch个投影运算符。

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 },
           ]
}

以下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 } ] }

$ 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

首页