Mongo聚合的具体格式

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

我试图在集合中分组数据后获得特定格式的输出。

集合中的数据如下所示:

[
{
  "country": "UK",
  "business": "computer",
  "companies": 24
},
{
  "country": "UK",
  "business": "automotive",
  "companies": 12
},
{
  "country": "US",
  "business": "medical",
  "companies": 3
},
{
  "country": "US",
  "business": "food",
  "companies": 53
}
]

我已经使用以下聚合来根据

business
country
进行分组:

[
  {
    $group: {
      _id: "$country",
      business: {
        $addToSet: "$business"
      }
    }
  }
]

我得到以下结果:

[
{
  "_id": "UK",
  "business": [ "computer", "automotive" ]
},
{
  "_id": "US",
  "business": [ "food", "medical" ]
}
]

我的问题:如何使用管道并将输出格式化为如下内容?

[
   {
      "US": {
         "business":[ "food", "medical" ]
      }
   },
   {
      "UK": {
         "business":[ "computer", "automotive" ]
      }
   }
]
mongodb aggregation-framework
1个回答
0
投票

一个选择是使用

$arrayToObject

db.collection.aggregate([
  {
    $group: {
      _id: "$country",
      business: {
        $addToSet: "$business"
      }
    }
  },
  {
    $project: {
      _id: 0,
      res: [
        {
          k: "$_id",
          v: {
            business: "$business"
          }
        }
      ]
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        "$arrayToObject": "$res"
      }
    }
  }
])

游乐场示例中查看它是如何工作的

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