mongodb Mongo将组数据聚合到单个文档中

yx2lnoni  于 2023-05-22  发布在  Go
关注(0)|答案(1)|浏览(129)

我从一个聚合组阶段得到了以下输出

[
 {
   "region": "region1",
   "business": "Electronics",
   "country": "US"
 },
 {
   "region": "region1",
   "business": "Medical",
   "country": "US"
 },
 {
   "region": "region1",
   "business": "Electronics",
   "country": "UK"
 },
 {
   "region": "region2",
   "business": "Automotive",
   "country": "Japan"
 },
 {
   "region": "region2",
   "business": "Food",
   "country": "China"
 }
]

我想合并输出如下:

[
 {
   "region": "region1",
   "business": [
      { "Electronics": ["UK", "US"] },
      { "Medical": ["US"] }
   ]
 },
 {
   "region": "region2",
   "business": [
      { "Automotive": ["Japan"] },
      { "Food": ["China"] }
   ]
 }
]

我可以在这里使用哪种聚合来动态地进行整合?

gopyfrb3

gopyfrb31#

1.按regionbusiness分组,并将country推入countries数组。
1.按region分组并推送键值对(k:business,v:countries)到business阵列中。
1.设置business字段以将每个键值对转换为对象并匹配所需的输出。

db.collection.aggregate([
  {
    $group: {
      _id: {
        region: "$region",
        business: "$business"
      },
      countries: {
        $push: "$country"
      }
    }
  },
  {
    $group: {
      _id: "$_id.region",
      business: {
        $push: {
          k: "$_id.business",
          v: "$countries"
        }
      }
    }
  },
  {
    $set: {
      business: {
        $map: {
          input: "$business",
          in: {
            $arrayToObject: [
              [
                "$$this"
              ]
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

相关问题