首页 > 解决方案 > MongoDB:从 ObjectId 更新为许多文档的字符串

问题描述

我有一个复杂的结构,类似于:

{
    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"}})

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

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

更新 对不起,我的结构更复杂:

data.content.$[element].otherStructure.testData.keys.$[element].values.$[element].meta.importantKey

所有这些$[element]元素都意味着具有元素列表的对象。

标签: databasemongodbmongodb-queryaggregation-frameworkmongoid

解决方案


您可以使用此解决方法:

db.collection.aggregate([
  {
    $addFields: {
      "data.content": {
        $map: {
          input: "$data.content",
          as: "data",
          in: {
            otherStructure: {
              testData: {
                keys: {
                  $map: {
                    input: "$$data.otherStructure.testData.keys",
                    as: "testData",
                    in: {
                      "values": {
                        $map: {
                          input: "$$testData.values",
                          as: "values",
                          in: {
                            "meta": {
                              "importantObject": {
                                "importantKey": {
                                  $toString: "$$values.meta.importantObject.importantKey"
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
{$out:"collection"}
])

Mongo游乐场


推荐阅读