首页 > 解决方案 > Mongodb - 按值分组并获取计数

问题描述

我有一个聚合查询,它返回类似的结果

    {
      count:1,
      status: 'FAILED',
      article_id: 1
    },
    {
      count:1,
      status: 'DELIVERED',
      article_id: 1
    }

我想按 article_id 分组并根据 status 获取计数,如下所示:

   {
      article_id:1,
      FAILED:1,
      DELIVERED:2
   }

我该如何存档?提前致谢。

标签: mongodbaggregation-framework

解决方案


其他答案原则上可能有效,但它们仅限于硬编码为 statusFAILEDDELIVERED.

如果您想为任意状态提供通用解决方案,您可以使用这个:

db.collection.aggregate([
   { $set: { data: [{ k: "$status", v: "$count" }] } },
   {
      $replaceRoot: {
         newRoot: {
            $mergeObjects: [
               { $arrayToObject: "$data" }, { article_id: "$article_id" }
            ]
         }
      }
   },
   {
      $group: {
         _id: "$article_id",
         status: { $push: "$$ROOT" }
      }
   },
   { $set: { status: { $mergeObjects: ["$status"] } } },
   { $replaceRoot: { newRoot: "$status" } },
])

蒙古游乐场


推荐阅读