如何在MongoDB中将String数组转换为Object数组

gdx19jrr  于 2023-04-29  发布在  Go
关注(0)|答案(1)|浏览(162)

如何进行聚合,将“资产”中的值拆分为单个对象?
这是我目前的目标:

[
      {
        "_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中使用聚合,并将字符串的“assets”数组中的值拆分为Object?firstkey、secondkey、thirdkey、fourthkey,它们可以在聚合查询中定义吗?

cgh8pdjw

cgh8pdjw1#

你可以这样做:

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等。.. afcourse如果你愿意,你可以提供并Map硬编码数组[“one”,“two”,“three”..]
Playgorund
这里是硬编码的字符串数组作为键:
Playgrouund2(arrayOfKeyStringHardCoded)
(只有5x个元素,但您可以根据需要进行扩展)

相关问题