Mongo shell> db.version:4.2.6
尝试使用以下方式更新集合中的所有文档:
类别数组[]。 ["value1", "value2"]
转换为 ["VALUE1", "VALUE2"]
通过使用占位符 $[e]
可以使用一些关于如何重写以下内容的帮助或解释。 谢谢。
db.Article.update( {},{ $set :{ "categories.$[e]" : { $toUpper: "e" }}},{ multi: true, arrayFilters : [ {"e" : { $regex:'.+' } } ]} )
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 52,
"errmsg" : "The dollar ($) prefixed field '$toUpper' in 'categories.0.$toUpper' is not valid for storage."
}
})
最佳答案
启动MongoDB版本>= 4.2
MongoDB中的更新操作可以在其中执行聚合管道,检查:update-with-an-aggregation-pipeline 。所以你可以尝试下面的查询:
db.Article.update(
{ $expr: { $eq: [{ $type: "$categories" }, "array"] } }, // Condition that checks `categories` exists & is an array.
[
{
$set: {
categories: {
$map: {
input: "$categories",
in: { $toUpper: "$$this" }
}
}
}
}
],
{ multi: true }
);
以防万一,如果 categories
数组中的几个元素不是 string 类型(如果 categories
数组是数字和字符串的混合) ) 然后在 $map
的 in
部分中,您可以有一个类似::{$cond : [{$eq : [{$type : '$$ this'},'string']},{ $toUpper: "$$this"} ,'$$this']}
测试:在此处测试聚合管道:mongoplayground
注意:您可以使用 .updateMany()
而不是使用带有选项 {multi : true} 的
..update()
关于mongodb - 通过 MongoDB 中的 collection.update 将所有数组值更新为Upper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577251/