本文描述另外一个典型的更新操作符 $[] ,其和 $ 操作符比较类似,用于更新指定数组字段的所有元素。体会:
modify all elements in the specified array field.
格式如下:
db.collection.updateMany(
{ <query conditions> },
{ <update operator>: { "<array>.$[]" : value } }
)
1:Update All Elements in an Array
注意,是一个数组的所有元素更改。
db.t.insertMany([
{ "_id" : 1, "grades" : [ 85, 82, 80 ] },
{ "_id" : 2, "grades" : [ 88, 90, 92 ] },
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
])
try {
$c->updateMany([],['$inc'=>["grades.$[]"=>10]],["multi"=>true]);
} catch (\Exception $e) {
print_r($e);
}
结果就是每个文档的grades数组元素都增加10。
2:Update All Documents in an Array
The $[] positional operator facilitates updates to arrays that contain embedded documents. To access the fields in the embedded documents, use the dot notation on the $[] operator.
注意,是更新一个数组中的内联文档,比如用notation符号指定某个字段。
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 8 },
{ "grade" : 85, "mean" : 90, "std" : 6 },
{ "grade" : 85, "mean" : 85, "std" : 8 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 8 },
{ "grade" : 87, "mean" : 90, "std" : 5 },
{ "grade" : 85, "mean" : 85, "std" : 6 }
]
}
下面的例子是更新所有数组中std内联文档值:
$c->updateMany([],['$inc'=>["grades.$[].std" => -2 ] ],[ "multi"=> true ] );
结果就是所有std值减2。
3:Update Arrays Specified Using a Negation Query Operator
使用否定操作符更新指定数组,比如:
$c->updateMany(["grades"=>["$ne"=>100]],['$inc'=>["grades.$[]" => -2 ] ],[ "multi"=> true ] );
grades数组中的值如果没有100的,则将所有元素值减2。
参考:https://docs.mongodb.com/manual/reference/operator/update/positional-all

文章转载自虞大胆的叽叽喳喳,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




