$ (update)

On this page本页内容

Definition定义

$

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.位置$运算符标识数组中要更新的元素,而不显式指定该元素在数组中的位置。

Note注意
Disambiguation消除歧义
  • To project, or return, an array element from a read operation, see the $ projection operator instead.要从读取操作投影或返回数组元素,请改为使用$投影运算符。
  • To update all elements in an array, see the all positional operator $[] instead.若要更新数组中的所有元素,请改为查看所有位置运算符$[]
  • To update all elements that match an array filter condition or conditions, see the filtered positional operator instead $[<identifier>].要更新与一个或多个数组筛选器条件匹配的所有元素,请参阅筛选的位置运算符,而不是$[<identifier>]

The positional $ operator has the form:位置$运算符的形式为:

{ "<array>.$" : value }

When used with update operations, e.g. db.collection.updateOne() and db.collection.findAndModify(),当与更新操作一起使用时,例如db.collection.updateOne()db.collection.findAndModify()

  • the positional $ operator acts as a placeholder for the first element that matches the query document, and位置$运算符充当与query文档匹配的第一个元素的占位符,并且
  • the array field must appear as part of the query document.array字段必须显示为query文档的一部分。

For example:例如:

db.collection.updateOne(
   { <array>: value ... },
   { <update operator>: { "<array>.$" : value } }
)

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,更新运算符以词典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. 具有数字名称的字段按数字顺序处理。See Update Operators Behavior for details.有关详细信息,请参阅更新运算符行为

upsert

Do not use the positional operator $ with upsert operations because inserts will use the $ as a field name in the inserted document.不要在upsert操作中使用位置运算符$,因为插入将使用$作为插入文档中的字段名。

Nested Arrays嵌套数组

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value位置$运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询。因为$占位符的替换是单个值

Unsets

When used with the $unset operator, the positional $ operator does not remove the matching element from the array but rather sets it to null.$unset运算符一起使用时,位置$运算符不会从数组中删除匹配元素,而是将其设置为空。

Negations否定

If the query matches the array using a negation operator, such as $ne, $not, or $nin, then you cannot use the positional operator to update values from this array.如果查询使用否定运算符(如$ne$not$nin)匹配数组,则不能使用位置运算符更新此数组中的值。

However, if the negated portion of the query is inside of an $elemMatch expression, then you can use the positional operator to update this field.但是,如果查询的否定部分在$elemMatch表达式中,则可以使用位置运算符更新此字段。

Multiple Array Matches多个数组匹配

The positional $ update operator behaves ambiguously when filtering on multiple array fields.在筛选多个数组字段时,位置$更新运算符的行为不明确。

When the server executes an update method, it first runs a query to determine which documents you want to update. 当服务器执行更新方法时,它首先运行查询以确定要更新哪些文档。If the update filters documents on multiple array fields, the subsequent call to the positional $ update operator doesn't always update the required position in the array.如果更新筛选了多个数组字段上的文档,那么对位置$更新运算符的后续调用并不总是更新数组中所需的位置。

For more information, see the example.有关更多信息,请参阅示例

Examples示例

Update Values in an Array更新数组中的值

Create a collection students with the following documents:使用以下文档创建students集合:

db.students.insertMany( [
   { "_id" : 1, "grades" : [ 85, 80, 80 ] },
   { "_id" : 2, "grades" : [ 88, 90, 92 ] },
   { "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

To update the first element whose value is 80 to 82 in the in the grades array, use the positional $ operator if you do not know the position of the element in the array:要更新grades数组中值为8082的第一个元素,如果不知道该元素在数组中的位置,请使用位置$运算符:

Important重要

You must include the array field as part of the query document.必须将数组字段作为query文档的一部分。

db.students.updateOne(
   { _id: 1, grades: 80 },
   { $set: { "grades.$" : 82 } }
)

The positional $ operator acts as a placeholder for the first match of the update query document.位置$运算符充当更新query文档第一个匹配的占位符。

After the operation, the students collection contains the following documents:操作后,students集合包含以下文档:

{ "_id" : 1, "grades" : [ 85, 82, 80 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

Update Documents in an Array更新数组中的文档

The positional $ operator facilitates updates to arrays that contain embedded documents. 位置$运算符有助于更新包含嵌入文档的数组。Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.使用位置$运算符访问嵌入文档中的字段,并在$运算符上使用点符号

db.collection.updateOne(
   { <query selector> },
   { <update operator>: { "array.$.field" : value } }
)

Consider the following document in the students collection whose grades element value is an array of embedded documents:考虑students集合中的以下文档,其grades元素值是嵌入文档的数组:

{
  _id: 4,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 85, mean: 85, std: 8 }
  ]
}

Use the positional $ operator to update the std field of the first array element that matches the grade equal to 85 condition:使用位置$运算符更新与grade等于85条件匹配的第一个数组元素的std字段:

Important重要

You must include the array field as part of the query document.必须将数组字段作为query文档的一部分。

db.students.updateOne(
   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)

After the operation, the document has the following updated values:操作后,文档具有以下更新值:

{
   "_id" : 4,
   "grades" : [
      { "grade" : 80, "mean" : 75, "std" : 8 },
      { "grade" : 85, "mean" : 90, "std" : 6 },
      { "grade" : 85, "mean" : 85, "std" : 8 }
   ]
}

Update Embedded Documents Using Multiple Field Matches使用多个字段匹配更新嵌入文档

The $ operator can update the first array element that matches multiple query criteria specified with the $elemMatch operator.$运算符可以更新与使用$elemMatch运算符指定的多个查询条件匹配的第一个数组元素。

Consider the following document in the students collection whose grades field value is an array of embedded documents:考虑students集合中的以下文档,其grades字段值是嵌入文档的数组:

{
  _id: 5,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 90, mean: 85, std: 3 }
  ]
}

In the example below, the $ operator updates the value of the std field in the first embedded document that has grade field with a value less than or equal to 90 and a mean field with a value greater than 80:在下面的示例中,$运算符更新第一个嵌入文档中的std字段的值,该文档中的grade字段的值小于或等于90mean字段的值大于80

db.students.updateOne(
   {
     _id: 5,
     grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
   },
   { $set: { "grades.$.std" : 6 } }
)

This operation updates the first embedded document that matches the criteria, namely the second embedded document in the array:此操作更新符合条件的第一个嵌入文档,即数组中的第二个嵌入文档:

{
  _id: 5,
  grades: [
    { grade: 80, mean: 75, std: 8 },
    { grade: 85, mean: 90, std: 6 },
    { grade: 90, mean: 85, std: 3 }
  ]
}

Update with Multiple Array Matches使用多个数组匹配进行更新

The positional $ update operator behaves ambiguously when the query has multiple array fields to filter documents in the collection.当查询具有多个数组字段以筛选集合中的文档时,位置$更新运算符的行为不明确。

Consider a document in the students_deans_list collection, which holds arrays of student information:考虑students_deans_list集合中的一个文档,其中包含学生信息数组:

db.students_deans_list.insertMany( [
   {
      _id: 8,
      activity_ids: [ 1, 2 ],
      grades: [ 90, 95 ],
      deans_list: [ 2021, 2020 ]
   }
] )

In the following example, the user attempts to modify the deans_list field, filtering documents using the activity_ids, deans_list, and grades fields, and updating the 2021 value in the deans_list field to 2022:在以下示例中,用户尝试修改deans_list字段,使用activity_idsdeans_listgrades字段筛选文档,并将deans_list字段中的2021值更新为2022:

db.students_deans_list.updateOne(
   { activity_ids: 1, grades: 95, deans_list: 2021 },
   { $set: { "deans_list.$": 2022 } }
)

When the server executes the updateOne method above, it filters the available documents using values in the supplied array fields. 当服务器执行上面的updateOne方法时,它使用提供的数组字段中的值筛选可用文档。Although the deans_list field is used in the filter, it is not the field used by the positional $ update operator to determine which position in the array to update:尽管筛选器中使用了deans_list字段,但它不是位置$更新运算符用于确定要更新数组中的哪个位置的字段:

db.students_deans_list.find( { _id: 8 } )

Example output:示例输出:

{
   _id: 8,
   activity_ids: [ 1, 2 ],
   grades: [ 90, 95 ],
   deans_list: [ 2021, 2022 ]
}

The updateOne method matched the deans_list field on 2021, but the positional $ update operator instead changed the 2020 value to 2022.updateOne方法在2021匹配了deans_list字段,但位置$更新运算符将2020值改为2022。

To avoid unexpected results when matching on multiple arrays, instead use the filtered positional operator $[<identifier>].为了避免在多个数组上进行匹配时出现意外结果,请改用筛选的位置运算符$[<identifier>]

←  Array Update Operators$[] →