$ (projection)

On this page本页内容

Definition定义

$

The positional $ operator limits the contents of an <array> to return the first element that matches the query condition on the array.位置$运算符限制<array>的内容,以返回与数组上的查询条件匹配的第一个元素。

Use $ in the projection document of the find() method or the findOne() method when you only need one particular array element in selected documents.如果在选定的文档中只需要一个特定的数组元素,请在find()方法的投影文档或findOne()方法中使用$

See the aggregation operator $filter to return an array with only those elements that match the specified condition.请参阅聚合运算符$filter以返回仅包含与指定条件匹配的元素的数组。

Note注意
Disambiguation消除歧义

To specify an array element to update, see the positional $ operator for updates.要指定要更新的数组元素,请参阅位置$运算符以获取更新

Usage Considerations使用注意事项

Both the $ operator and the $elemMatch operator project the first matching element from an array based on a condition.$运算符和$elemMatch运算符都根据条件从数组中投影第一个匹配元素。

The $ operator projects the first matching array element from each document in a collection based on some condition from the query statement.$运算符根据查询语句中的某些条件,从集合中的每个文档投影第一个匹配的数组元素。

The $elemMatch projection operator takes an explicit condition argument. $elemMatch投影运算符采用显式条件参数。This allows you to project based on a condition not in the query, or if you need to project based on multiple fields in the array's embedded documents. 这允许您基于查询中没有的条件进行投影,或者如果需要基于数组嵌入文档中的多个字段进行投影,也可以进行投影。See Array Field Limitations for an example.有关示例,请参阅数组字段限制

db.collection.find() operations on views do not support $ projection operator.视图上的操作不支持$projection运算符。

Behavior行为

Syntax语法

To return the first array element that matches the specified query condition on the array:要返回与数组上的指定查询条件匹配的第一个数组元素,请执行以下操作:

db.collection.find( { <array>: <condition> ... },
                    { "<array>.$": 1 } )
db.collection.find( { <array.field>: <condition> ...},
                    { "<array>.$": 1 } )

Changed in version 4.4.在版本4.4中更改

You can use the $ operator to limit an <array> field which does not appear in the query document. 可以使用$运算符限制查询文档中未出现的<array>字段。In previous versions of MongoDB, the <array> field being limited must appear in the query document.在MongoDB的早期版本中,受限的<array>字段必须出现在查询文档中。

db.collection.find( { <someOtherArray>: <condition> ... },
                    { "<array>.$" : 1 } )
Important重要

To ensure expected behavior, the arrays used in the query document and the projection document must be the same length. 为了确保预期的行为,查询文档和投影文档中使用的数组必须具有相同的长度。If the arrays are different lenghts, the operation may error in certain scenarios.如果数组的长度不同,则在某些情况下操作可能会出错。

Array Field Limitations数组字段限制

MongoDB requires the following when dealing with projection over arrays:MongoDB在处理数组上的投影时需要以下内容:

  • Only one positional $ operator may appear in the projection document.投影文档中只能出现一个位置$运算符。
  • Only one array field should appear in the query document. 查询文档中只应显示一个数组字段。Additional array fields in the query document may lead to undefined behavior.查询文档中的其他数组字段可能会导致未定义的行为。

    For example, the following projection may lead to undefined behavior:例如,以下投影可能会导致未定义的行为:

    db.collection.find( { <array>: <value>, <someOtherArray>: <value2> },
                        { "<array>.$": 1 } )
  • The query document should only contain a single condition on the array field to which it is applied. 查询文档应仅在应用它的数组字段上包含一个条件。Multiple conditions may override each other internally and lead to undefined behavior.多个条件可能会在内部相互覆盖,并导致未定义的行为。

    To specify criteria on multiple fields of documents inside that array, use the $elemMatch query operator. 要在该数组内的多个文档字段上指定条件,请使用$elemMatch查询运算符。The following query returns the first document inside a grades array that has a mean of greater than 70 and a grade of greater than 90.以下查询返回mean大于70且grade大于90的等级数组内的第一个文档。

    db.students.find( { grades: { $elemMatch: {
                                                mean: { $gt: 70 },
                                                grade: { $gt:90 }
                                              } } },
                      { "grades.$": 1 } )

    You must use the $elemMatch operator if you need separate conditions for selecting documents and for choosing fields within those documents.如果选择文档和选择文档中的字段需要单独的条件,则必须使用$elemMatch运算符。

Sorts and the Positional Operator排序和位置运算符

When the find() method includes a sort(), the find() method applies the sort() to order the matching documents before it applies the positional $ projection operator.find()方法包含一个sort()时,find()方法在应用位置$投影运算符之前,先应用sort()来排序匹配的文档。

If an array field contains multiple documents with the same field name and the find() method includes a sort() on that repeating field, the returned documents may not reflect the sort order because the sort was applied to the elements of the array before the $ projection operator.如果数组字段包含多个具有相同字段名的文档,并且find()方法在该重复字段上包含一个sort(),则返回的文档可能不会反映排序顺序,因为排序是在$投影运算符之前应用于数组的元素。

Positional Operator Placement Restriction位置运算符安置限制

Starting in MongoDB 4.4, the $ projection operator can only appear at the end of the field path; e.g. "field.$" or "fieldA.fieldB.$".从MongoDB 4.4开始,$投影运算符只能出现在字段路径的末尾;例如"field.$""fieldA.fieldB.$"

For example, starting in MongoDB 4.4, the following operation is invalid:例如,从MongoDB 4.4开始,以下操作无效:

db.inventory.find( { }, { "instock.$.qty": 1 } ) // Invalid starting in 4.4

To resolve, remove the component of the field path that follows the $ projection operator.要解决此问题,请删除遵循$投影运算符的字段路径的组件。

In previous versions, MongoDB ignores the part of the path that follows the $; i.e. the projection is treated as "instock.$".在以前的版本中,MongoDB忽略$;后面的路径部分;即,投影被视为"instock.$"

Positional Operator and $slice Restriction位置运算符和$slice限制

Starting in MongoDB 4.4, find and findAndModify projection cannot include $slice projection expression as part of a $ projection expression.从MongoDB 4.4开始,findfindAndModify投影不能包含$slice投影表达式作为$投影表达式的一部分。

For example, starting in MongoDB 4.4, the following operation is invalid:例如,从MongoDB 4.4开始,以下操作无效:

db.inventory.find( { "instock.qty": { $gt: 25 } }, { "instock.$": { $slice: 1 } } ) // Invalid starting in 4.4

In previous versions, MongoDB returns the first element (instock.$) in the instock array that matches the query condition; i.e. the positional projection "instock.$" takes precedence and the $slice:1 is a no-op. 在以前的版本中,MongoDB返回instock数组中匹配查询条件的第一个元素(instock.$);即,位置投影"instock.$"优先,$slice:1是no-op。The "instock.$": { $slice: 1 } does not exclude any other document field."instock.$": { $slice: 1 }不排除任何其他文档字段。

Examples示例

Project Array Values项目数组值

A collection students contains the following documents:集合students包含以下文档:

{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }
{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] }
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }

In the following query, the projection { "grades.$": 1 } returns only the first element greater than or equal to 85 for the grades field.在下面的查询中,投影{ "grades.$": 1 }只为grades字段返回大于或等于85的第一个元素。

db.students.find( { semester: 1, grades: { $gte: 85 } },
                  { "grades.$": 1 } )

The operation returns the following documents:该操作返回以下文档:

{ "_id" : 1, "grades" : [ 87 ] }
{ "_id" : 2, "grades" : [ 90 ] }
{ "_id" : 3, "grades" : [ 85 ] }

Although the array field grades may contain multiple elements that are greater than or equal to 85, the $ projection operator returns only the first matching element from the array.尽管数组字段grades可能包含多个大于或等于85的元素,但$投影运算符仅返回数组中的第一个匹配元素。

Project Array Documents项目数组文档

A students collection contains the following documents where the grades field is an array of documents; each document contain the three field names grade, mean, and std:students集合包含以下文档,其中grades字段是一组文档;每个文档包含三个字段名grademeanstd

{ "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 },
                                       { grade: 85, mean: 90, std: 5 },
                                       { grade: 90, mean: 85, std: 3 } ] }
{ "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 },
                                       { grade: 78, mean: 90, std: 5 },
                                       { grade: 88, mean: 85, std: 3 } ] }

In the following query, the projection { "grades.$": 1 } returns only the first element with the mean greater than 70 for the grades field:在以下查询中,投影{ "grades.$": 1 }仅为grades字段返回mean大于70的第一个元素:

db.students.find(
   { "grades.mean": { $gt: 70 } },
   { "grades.$": 1 }
)

The operation returns the following documents:该操作返回以下文档:

{ "_id" : 7, "grades" : [  {  "grade" : 80,  "mean" : 75,  "std" : 8 } ] }
{ "_id" : 8, "grades" : [  {  "grade" : 92,  "mean" : 88,  "std" : 8 } ] }

Further Reading进一步阅读

$elemMatch (projection)

←  Projection Operators$elemMatch (projection) →