Database Manual / Reference / Query Language / Update / Arrays

$[<identifier>] (filtered positional update operator)(经过筛选的位置更新运算符)

Definition定义

$[<identifier>]

The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation, e.g. db.collection.updateMany() and db.collection.findAndModify().筛选后的位置运算符$[<identifier>]标识与更新操作的arrayFilters条件匹配的数组元素,例如db.collection.updateMany()db.collection.findAndModify()

Used in conjunction with the arrayFilters option, the $[<identifier>] operator has the following form:arrayFilters选项结合使用时,$[<identifier>]运算符具有以下形式:

{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }

Use in conjunction with the arrayFilters option to update all elements that match the arrayFilters conditions in the document or documents that match the query conditions. For example:arrayFilters选项结合使用,可以更新文档中与arrayFilters条件匹配的所有元素。例如:

db.collection.updateMany(
{ <query conditions> },
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }
)

Note

The <identifier> must begin with a lowercase letter and contain only alphanumeric characters.<identifier>必须以小写字母开头,并且只能包含字母数字字符。

For an example, see Update All Array Elements That Match arrayFilters.例如,请参阅更新与arrayFilters匹配的所有数组元素

Behavior行为

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

Restrictions限制

The arrayFilters option cannot include the following query operators:arrayFilters选项不能包含以下查询运算符:

upsert

If an upsert operation results in an insert, the query must include an exact equality match on the array field in order to use $[<identifier>] in the update statement.如果upsert操作导致插入,则query必须在数组字段上包含完全相等的匹配,以便在更新语句中使用$[<identifier>]

For example, the following upsert operation, which uses $[<identifier>] in the update document, specifies an exact equality match condition on the array field:例如,以下在更新文档中使用$[<identifier>]的追加销售操作在数组字段上指定了一个完全相等的匹配条件:

db.collection.updateOne(
{ myArray: [ 0, 1 ] },
{ $set: { "myArray.$[element]": 2 } },
{ arrayFilters: [ { element: 0 } ], upsert: true }
)

If no such document exists, the operation would result in an insert of a document that resembles the following:如果不存在此类文档,则该操作将导致插入类似以下内容的文档:

{ "_id" : ObjectId(...), "myArray" : [ 2, 1 ] }

If the upsert operation did not include an exact equality match and no matching documents were found to update, the upsert operation would error. For example, the following operations would error if no matching documents were found to update:如果追加销售操作不包括完全相等的匹配,并且找不到要更新的匹配文档,则追加销售操作将出错。例如,如果找不到要更新的匹配文档,则以下操作将出错:

db.array.updateOne(
{ },
{ $set: { "myArray.$[element]": 10 } },
{ arrayFilters: [ { element: 9 } ], upsert: true }
)

The operation would return an error that resembles the following:该操作将返回类似以下内容的错误:

MongoServerError: The path 'myArray' must exist in the document in order to apply array updates.

Nested Arrays嵌套数组

The filtered positional operator $[<identifier>] can be used for queries which traverse more than one array and nested arrays.筛选后的位置运算符$[<identifier>]可用于遍历多个数组和嵌套数组的查询。

For an example, see Update Nested Arrays in Conjunction with $[].例如,请参阅$[]结合更新嵌套数组

Examples示例

Update All Array Elements That Match arrayFilters更新与arrayFilters匹配的所有数组元素

Create the students collection:创建students集合:

db.students.insertMany( [
{ "_id" : 1, "grades" : [ 95, 92, 90 ] },
{ "_id" : 2, "grades" : [ 98, 100, 102 ] },
{ "_id" : 3, "grades" : [ 95, 110, 100 ] }
] )

To update all elements that are greater than or equal to 100 in the grades array, use the filtered positional operator $[<identifier>] with the arrayFilters:要更新grades数组中大于或等于100的所有元素,请在arrayFilters中使用筛选位置运算符$[<identifier>]

db.students.updateMany(
{ },
{ $set: { "grades.$[element]" : 100 } },
{ arrayFilters: [ { "element": { $gte: 100 } } ] }
)

The positional $[<identifier>] operator acts as a placeholder for all elements in the array field that match the conditions specified in arrayFilters.位置$[<identifier>]运算符充当数组字段中与arrayFilters中指定的条件匹配的所有元素的占位符。

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

{ "_id" : 1, "grades" : [ 95, 92, 90 ] }
{ "_id" : 2, "grades" : [ 98, 100, 100 ] }
{ "_id" : 3, "grades" : [ 95, 100, 100 ] }

Update All Documents That Match arrayFilters in an Array更新与数组中的arrayFilters匹配的所有文档

The $[<identifier>] operator facilitates updates to arrays that contain embedded documents. To access the fields in the embedded documents, use the dot notation with the $[<identifier>].$[<identifier>]运算符便于更新包含嵌入式文档的数组。要访问嵌入文档中的字段,请使用带有$[<identifier>]点符号

db.collection.updateMany(
{ <query selector> },
{ <update operator>: { "array.$[<identifier>].field" : value } },
{ arrayFilters: [ { <identifier>: <condition> } } ] }
)

Create the students2 collection:创建students2集合:

db.students2.insertMany( [
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 90, "std" : 4 },
{ "grade" : 85, "mean" : 85, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 6 },
{ "grade" : 87, "mean" : 90, "std" : 3 },
{ "grade" : 85, "mean" : 85, "std" : 4 }
]
}
] )

To modify the value of the mean field for all elements in the grades array where the grade is greater than or equal to 85, use the positional $[<identifier>] operator and arrayFilters:要修改grades数组中等级大于或等于85的所有元素的mean(均值)字段的值,请使用位置$[<identifier>]]运算符和arrayFilters

db.students2.updateMany(
{ },
{ $set: { "grades.$[elem].mean" : 100 } },
{ arrayFilters: [ { "elem.grade": { $gte: 85 } } ] }
)

After the operation, the collection has the following documents:操作后,集合有以下文件:

{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 6 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 100, "std" : 6 },
{ "grade" : 87, "mean" : 100, "std" : 3 },
{ "grade" : 85, "mean" : 100, "std" : 4 }
]
}

Update All Array Elements that Match Multiple Conditions更新匹配多个条件的所有数组元素

Create the students3 collection:创建students3集合:

db.students3.insertMany( [
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 100, "std" : 6 },
{ "grade" : 87, "mean" : 100, "std" : 3 },
{ "grade" : 85, "mean" : 100, "std" : 4 }
]
}
] )

To modify the value of the std field for all elements in the grades array where both the grade is greater than or equal to 80 and the std is greater than or equal to 5, use the positional $[<identifier>] operator and arrayFilters:要修改grades数组中所有元素的std字段的值,其中grade大于或等于80std大于或等于5,请使用位置$[<identifier>]运算符和arrayFilters

db.students3.updateMany(
{ },
{ $inc: { "grades.$[elem].std" : -1 } },
{ arrayFilters: [ { "elem.grade": { $gte: 80 }, "elem.std": { $gte: 5 } } ] }
)

After the operation, the collection has the following documents:操作后,集合有以下文件:

{  "_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 5 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 5 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 100, "std" : 5 },
{ "grade" : 87, "mean" : 100, "std" : 3 },
{ "grade" : 85, "mean" : 100, "std" : 4 }
]
}

Update Array Elements Using a Negation Operator使用否定运算符更新数组元素

Create the alumni collection:创建alumni(校友)集合:

db.alumni.insertMany( [
{
"_id": 1,
"name": "Christine Franklin",
"degrees": [
{ "level": "Master" },
{ "level": "Bachelor" }
],
},
{
"_id": 2,
"name": "Reyansh Sengupta",
"degrees": [ { "level": "Bachelor" } ],
}
] )

To modify all elements in the degrees array that do not have "level": "Bachelor", use the positional $[<identifier>] operation with the $ne query operator:要修改degrees数组中没有"level": "Bachelor"的所有元素,请使用位置$[<identifier>]操作和$ne查询运算符:

db.alumni.updateMany(
{ },
{ $set : { "degrees.$[degree].gradcampaign" : 1 } },
{ arrayFilters : [ {"degree.level" : { $ne: "Bachelor" } } ] }
)

After the operation, the collection has the following documents:操作后,集合有以下文件:

 {
_id: 1,
name: 'Christine Franklin',
degrees: [
{ level: 'Master', gradcampaign: 1 },
{ level: 'Bachelor' }
]
},
{
_id: 2,
name: 'Reyansh Sengupta',
degrees: [ { level: 'Bachelor' } ]
}

Update Nested Arrays in Conjunction with $[]$[]一起更新嵌套数组

The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays.$[<identifier>]筛选位置运算符与$[]全位置运算符结合使用,可用于更新嵌套数组。

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

db.students4.insertOne(
{ "_id" : 1,
"grades" : [
{ type: "quiz", questions: [ 10, 8, 5 ] },
{ type: "quiz", questions: [ 8, 9, 6 ] },
{ type: "hw", questions: [ 5, 4, 3 ] },
{ type: "exam", questions: [ 25, 10, 23, 0 ] },
]
}
)

The following updates the values that are greater than or equal to 8 in the nested grades.questions array if the associated grades.type field is quiz.如果关联的grades.type字段为quiz(测验),则以下内容将更新嵌套grades.questions数组中大于或等于8的值。

db.students4.updateMany(
{},
{ $inc: { "grades.$[t].questions.$[score]": 2 } },
{ arrayFilters: [ { "t.type": "quiz" }, { "score": { $gte: 8 } } ] }
)

Note

Don't add spaces around the array identifiers. If you use grades.$[ t ].questions.$[ score ] in the previous example, the example fails.不要在数组标识符周围添加空格。如果你在前面的示例中使用grades.$[ t ].questions.$[ score ],该示例失败。

After the operation, the collection has the following document:操作后,集合具有以下文档:

{
"_id" : 1,
"grades" : [
{ "type" : "quiz", "questions" : [ 12, 10, 5 ] },
{ "type" : "quiz", "questions" : [ 10, 11, 6 ] },
{ "type" : "hw", "questions" : [ 5, 4, 3 ] },
{ "type" : "exam", "questions" : [ 25, 10, 23, 0 ] }
]
}

To update all values that are greater than or equal to 8 in the nested grades.questions array, regardless of type:要更新嵌套grades.questions数组中大于或等于8的所有值,无论其type如何:

db.students4.updateMany(
{},
{ $inc: { "grades.$[].questions.$[score]": 2 } },
{ arrayFilters: [ { "score": { $gte: 8 } } ] }
)

Learn More了解更多

For examples that use the $[<identifier>] operator to update arrays, see Update Array Elements in a Document with MQL Positional Operators.有关使用$[<identifier>]运算符更新数组的示例,请参阅使用MQL位置运算符更新文档中的数组元素