首页 > 解决方案 > MongoDB:如何根据其他字段更新数组元素的字段?

问题描述

我正在尝试通过使用带有管道的更新来更新我的 MongoDB (4.2) 中的数据。困难在于我想根据另一个字段向数组元素添加一个字段。我也想对每个元素都这样做。我知道我可以用 Javascript 来做每一个,但我想知道是否有更好的方法。所以这就是我想要做的一个例子

前:

{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim"
            },
            "text" : "also text"
        }
    ]
}

{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John",
                "newId" : "00012345"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim",
                "newId" : "00056789"
            },
            "text" : "also text"
        }
    ]
}

我尝试了什么:

db.mail.update(
   {"_id" : ObjectId("555555555")},
  [{ $set: { "messages.$[].author.newId": { $concat: [ "000", "$messages.$[].author.userId"]}}}],
  { multi: true, writeConcern: {w: 0} }
)

有谁知道如何解决这个问题?谢谢

标签: mongodbmongodb-query

解决方案


这将执行所需的更新。

db.test.update(
  { _id : ObjectId("555555555") },
  [ 
    { 
      $set: { 
          messages: {
              $map: {
                   input: "$messages",
                   in: {
                       $mergeObjects: [
                           "$$this",
                           { "author": { 
                                  $mergeObjects: [ 
                                       "$$this.author", 
                                       { newId: { $concat: [ "000", "$$this.author.userId"] } } 
                                   ]
                           } }
                       ]
                   }
              } 
          }
      }
    }
  ],
  { multi: true, writeConcern: {w: 0} }
)

请注意,$[]当不使用聚合时,数组更新的所有位置运算符将与更新操作一起使用。当字段值依赖于文档中的另一个字段时,您必须使用聚合来更新。


推荐阅读