首页 > 解决方案 > 获取一个键/值对象,其中键是一个值的枚举

问题描述

在 MongoDB 中,如何获取键/值对象,其中每个键是枚举的值,值是具有枚举值的文档数。

总之,

db={
  "orders": [
    { "_id": 1, "type": "news" },
    { "_id": 2, "type": "news" },
    { "_id": 3, "type": "news" },
    { "_id": 4, "type": "alert" },
    { "_id": 5, "type": "alert" }
  ]
}

我怎样才能得到这个:

{
    news: 3,
    alert: 2 
}

我正在使用带有组的聚合,如下所示:

db.orders.aggregate([
  {
    "$group": {
      "_id": "$type",
      "count": { "$sum": 1 }
    }
  }
]);

我明白了:

[
  { "_id": 'alert', "count": 2 },
  { "_id": 'news', "count": 3 }
]

但是从那里开始,我不知道如何转换文档以获得上述预期结果。

Ty 提前!

标签: mongodbmongoose

解决方案


像这样的聚合将起作用:

db.orders.aggregate([
  {
    "$group": {
      "_id": "$type",
      "count": { "$sum": 1 }
    }
  },
  {
    "$group" : {
      "_id": null,
      "array": {  
        "$push": { "k": "$_id", "v": "$count"}
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": { "$arrayToObject": "$array"}
    }
  }
])

第二$group阶段包含表单对象的数组{ k: type, v: count }。这是为了让操作员$arrayToObject可以使用它。

然后$replaceRoot阶段用于$arrayToObject以所需格式输出结果。


推荐阅读