通过MongoDB中的collection.update将所有数组值更新到Upper



Mongo-shell>数据库版本:4.2.6

正在尝试使用以下内容更新集合中的所有文档:categories数组[]。["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中启动MongoDB版本>=4.2更新操作可以在其中执行聚合管道,检查:使用聚合管道更新。所以您可以尝试以下查询:

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数组是数字和字符串的混合(,那么在$mapin部分中,您可以有一个条件,如:{$cond : [{$eq : [{$type : '$$this'},'string']},{ $toUpper: "$$this" } ,'$$this']}

测试:此处测试聚合管道:mongoplayground

注意:您可以使用.updateMany(),而不是使用带有选项{multi : true}.update()

最新更新