MongoDB:从许多文件的ObjectId更新为字符串

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

我的复杂结构类似于:

{
    type: "Data",
    data: [
      "item1": {...},
      "item2": {...},
      ...
      "itemN": {
          "otherStructure": {
              "testData": [
                  {
                      "values": {...}
                  },

                  {
                      "values": {
                          "importantKey": ObjectId("23a2345gf651")
                      }
                  }
              ]
          }
      }
    ]
}

对于这种数据结构,我想将所有这些importantKeys的数据类型从ObjectId更新为字符串。

我正在尝试类似的查询:

db.collection.updateMany(
{type:"Data"},
{$toString: "data.$[element].otherStructure.testData.$[element].values.importantKey"},
{"data.element.otherStructure.testData.element.values.importantKey": {$type: "objectId"}})

但是所有这些尝试都没有成功。

那么,是否有适当的解决方案来更新此类数据?

database mongodb mongodb-query aggregation-framework mongoid
1个回答
0
投票

您可以使用此解决方法:

db.collection.aggregate([
  {
    $addFields: {
      data: {
        $map: {
          input: "$data",
          as: "data",
          in: {
            item: {
              $map: {
                input: "$$data.item.otherStructure.testData",
                as: "testData",
                in: {
                  "values": {
                    "importantKey": {
                      $toString: "$$testData.values.importantKey"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  {
    $out: "collection"
  }
])
© www.soinside.com 2019 - 2024. All rights reserved.