mongodb:将对象与数组展平/合并为集合中所有文档的单个数组

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

我的收藏中有以下文档结构:

问题:

{
  "fruits": {
    "brasil": [
      "pineapple",
      "mango",
    ],
    "france": [
      "apple",
      "grape"
    ],
  },
}

目标:

{
  "fruits": [
    "brasil_pineapple",
    "brasil_mango",
    "france_apple",
    "france_grape"
  ]
}

为了更容易处理,我想将水果的值减少到一个列表,其中包含对象“水果”中键值的所有列表,并在每个列表项前加上相应的键以保持唯一性。

如何将所有文档转换为所需的文档结构?

感谢您的帮助!

mongodb mongodb-query pymongo
1个回答
0
投票

正如评论中提到的@rickhg12hs,您可能需要考虑另一种模式以便于处理。不过,对于您当前提出的架构,您可以使用

$objectToArray
fruits
转换为 k-v 元组数组,并使用
$reduce
$map
迭代数组。

db.collection.aggregate([
  {
    "$set": {
      "fruits": {
        "$objectToArray": "$fruits"
      }
    }
  },
  {
    $set: {
      fruits: {
        "$reduce": {
          "input": "$fruits",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              {
                "$map": {
                  "input": "$$this.v",
                  "as": "f",
                  "in": {
                    $concat: [
                      "$$this.k",
                      "_",
                      "$$f"
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Mongo 游乐场

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