如何在 MongoDB 中将字符串数组转换为对象数组

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

如何进行聚合以将“资产”中的值拆分为单个对象?

这是我现在的对象:

   [
      {
        "_id": ObjectId("5c949609ff5e3d6119758730"),
        "assets": [
          "one##two##three##four",
          "one##two##hello##world"
        ]
      }
    ]

预期:

[
  {
    "_id": ObjectId("5c949609ff5e3d6119758730"),
    "assets": [
        {
            "firstkey": "one",
            "secondkey": "two",
            "thirdkey: "three",
            "fourthkey": "four          
        },
        {
            "firstkey": "one",
            "secondkey": "five",
            "thirdkey: "hello",
            "fourthkey": "world         
        }
    ]
  }
]

如何在 MongoDB 中使用聚合并将“资产”字符串数组中的值溢出到对象中? firstkey, secondkey, thirdkey, fourthkey,它们可以在聚合查询中定义吗?

mongodb aggregation-framework
1个回答
0
投票

你可以这样做:

db.collection.aggregate([
{
 $addFields: {
  assets: {
    "$map": {
      "input": "$assets",
      "as": "s",
      "in": {
        obj: {
          "$map": {
            "input": {
              "$split": [
                "$$s",
                "##"
              ]
            },
            "as": "a",
            "in": {
              v: "$$a"
            }
          }
        }
      }
    }
  }
 }
},
{
$addFields: {
  assets: {
    "$map": {
      "input": "$assets",
      "as": "a",
      "in": {
        $map: {
          input: {
            $range: [
              0,
              {
                $size: "$$a.obj"
              }
            ]
          },
          as: "idx",
          in: {
            $mergeObjects: [
              {
                $arrayElemAt: [
                  "$$a.obj",
                  "$$idx"
                ]
              },
              {
                $arrayElemAt: [
                  {
                    "$map": {
                      "input": {
                        "$range": [
                          0,
                          {
                            $size: "$$a.obj"
                          },
                          1
                        ]
                      },
                      "as": "key",
                      "in": {
                        k: {
                          "$concat": [
                            "key",
                            {
                              "$toString": "$$key"
                            }
                          ]
                        }
                      }
                    }
                  },
                  "$$idx"
                ]
              }
            ]
          }
        }
      }
    }
  }
  }
 },
 {
"$addFields": {
  "assets": {
    "$map": {
      "input": "$assets",
      "as": "a",
      "in": {
        "$arrayToObject": "$$a"
      }
    }
   }
  }
 }
 ])

解释: 这将为您提供 key0、key1 等... 当然,如果你愿意,你可以提供并映射硬编码数组 ["one","two","three"..]

Playgorund

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