【问题标题】:MongoDB - How to modify the "key" element in the documentMongoDB - 如何修改文档中的“key”元素
【发布时间】:2022-08-03 07:59:16
【问题描述】:

我有以下文档结构:

[
  {
    \"network_type\": \"ex\",
    \"rack\": [
      {
        \"xxxx\": {
          \"asn\": 111111,
          \"nodes\": {
            \"business\": [
              \"sk550abcc1eb01.abc.com\",
              \"sk550abcc1eb10.abc.com\",
              \"sk550abcc1eb19.abc.com\",
              \"sk550abcc1eb28.abc.com\"
            ]
          },
          \"region\": \"ex-01\",
          \"zone\": \"01a\"
        }
      }
    ]
  }
]

我需要将键数组元素 \"xxxx\" 重命名/更新为 \"details\"。

我尝试了以下命令,但它似乎不起作用。

db.collection.update({},
{
  $rename: {
    \"rack.xxxx\": \"details\"
  }
})

链接:https://mongoplayground.net/p/9dcDP-VKZ55

请帮我。

    标签: arrays mongodb mongodb-query rename mongodb-update


    【解决方案1】:

    您不能直接$rename 数组中的字段名称。

    反而,

    1. 迭代rank 数组中的文档,创建值为xxxxdetails 字段,然后将此字段附加到每个文档。

    2. 删除带有$rank.xxxx 的路径以从rank 数组中的文档中删除xxxx 字段。

      db.collection.update({},
      [
        {
          $set: {
            rack: {
              $map: {
                input: "$rack",
                in: {
                  $mergeObjects: [
                    {
                      "details": "$$this.xxxx"
                    },
                    "$$this"
                  ]
                }
              }
            }
          }
        },
        {
          $unset: "rack.xxxx"
        }
      ])
      

      Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多