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

问题描述 投票:1回答:1

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 mongodb-query aggregation-framework
1个回答
0
投票

开始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 }
);

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

注意:您可以使用.updateMany()代替将.update()与选项{multi : true}一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.