在对集合中的数据进行分组后,我正在try 获取特定格式的输出.

集合中的数据如下所示:

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

我使用了以下聚合来根据countrybusiness进行分组:

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

我得到了以下结果:

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

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

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

推荐答案

一种 Select 是使用$arrayToObject:

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

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

Mongo,通过 Lookup 计算多个文档中数组中的项目

MongoDB:通过嵌套数组中的最后一个元素值获取文档

如何在mongodb中级联删除文档?

MongoDB查询仅返回嵌入文档

mongoose中的 required是什么意思?

使用 Node.js 通过 SSL 连接到 MongoDB

替换 MongoDB 中数组中的嵌入文档

node.js & express - 应用程序 struct 的全局模块和最佳实践

Mongodb 仅在值唯一时插入,否则更新 - 在 node.js 中

为什么 local.oplog.rs 上每隔几分钟的活动就会锁定 mongo 客户端

通过 Spring Boot 应用程序访问 mongodb 时的身份验证错误

在 Nodejs 中配置最大旧空间大小

Mongoose 的保存回调是如何工作的?

如何使用 java 驱动程序更新 mongo db 中的文档字段?

嵌套数组内的Mongodb增量值

如何解决 ClassNotFoundException:com.mongodb.connection.BufferProvider?

带有排序功能的mongoose findOne

无法从 MongoDb C# 中的 BsonType ObjectId 反序列化字符串

Mongoose upsert 不创建默认模式属性

即使重新安装后,Mongo 仍在等待 27017