如何将嵌入文档数组中的值带入 MongoDB 的根目录?

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

我有以下记录:

id: 119,
customfields: Array (2)

  0: Object
    value: "Mr"
    type: "salutation"

  1: Object
    value: "Google"
    type: "company"

我需要更新此文档以便我得到:


id: 119,
salutation: "Mr",
company: "Google"

重要的是

  • 参数的位置可能会有所不同,即某些记录首先具有
    salutation
    ,其他记录具有
    company
    ,而其他记录可能具有其他无关紧要的字段。
  • 某些文档在
    salutation
    数组内没有
    customfields
    记录,因此应被忽略。公司的逻辑也一样。
mongodb mongodb-query aggregation-framework
2个回答
1
投票
首先

$map
customfields
到 k-v 元组数组。然后,
$mergeObjects
$$ROOT
对象得到最终对象。
$unset
现在无用的自定义字段和
$merge
通过
id
更新回文档。

db.collection.aggregate([
  {
    "$match": {
      "id": 119
    }
  },
  {
    "$set": {
      "customfields": {
        "$arrayToObject": {
          "$map": {
            "input": "$customfields",
            "as": "cf",
            "in": {
              "k": "$$cf.type",
              "v": "$$cf.value"
            }
          }
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$customfields"
        ]
      }
    }
  },
  {
    "$unset": "customfields"
  },
  {
    "$merge": {
      "into": "collection",
      "on": "id"
    }
  }
])

蒙戈游乐场


0
投票

这是另一种方法,使用

"$reduce"
重建文档。

db.collection.update({
  "id": 119
},
[
  {
    "$set": {
      "newRoot": {
        "$reduce": {
          "input": "$customfields",
          "initialValue": {
            "id": "$id"
          },
          "in": {
            "$mergeObjects": [
              "$$value",
              {
                "$arrayToObject": [
                  [
                    {
                      "k": "$$this.type",
                      "v": "$$this.value"
                    }
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  },
  {"$replaceWith": "$newRoot"}
])

mongoplayground.net 上尝试一下。

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