【问题标题】:mongodb Aggregate for already grouped distinct combination (grouping inside grouping)mongodb聚合已经分组的不同组合(分组内分组)
【发布时间】:2019-04-01 16:49:24
【问题描述】:

我正在使用 mongoDB,其中我收集了以下格式。

{name : x  city : AAA , status : active , radius : 1 }
{name : x  city : AAA , status : active , radius : 4  }
{name : x  city : AAA , status : inactive , radius : 7 }
{name : x  city : BBB , status : inactive , radius : 7 }
{name : Y  city : AAA , status : active , radius : 8 }
{name : Y  city : BBB , status : inactive , radius : 5 }
{name : Y  city : BBB , status : inactive , radius : 12 }
{name : Z  city : CCC , status : deleted , radius : 15 }

现在我想要 nameclass 的唯一组合,并且对于该组合​​还需要状态字段的 active 、 inactive 和 deleted 计数的子分组。因此整体输出报告将采用以下格式

Name  City  total  Active  Inactive deleted 
 X     AAA    3     2       1         0
 X     BBB    1     0       1         0
 Y     AAA    1     1       0         0
 Y     BBB    2     0       2         0
 Z     CCC    1     0       0         1

由于我是 mongodb 的新手,因此任何人都可以建议有什么方法可以使用聚合或任何其他方法以最少的查询获得所需的输出格式?

【问题讨论】:

  • 你的意思是 city 而不是 class?如果是,请编辑

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您只需要一个$group 阶段,按名称和城市分组,以及activeinactivedeleted 字段中的每个字段的条件总和。然后你在最后添加一个$project 阶段只是为了得到你想要的确切格式。

db.collection.aggregate([
  {
    $group: {
      "_id": {
        name: "$name",
        city: "$city"
      },
      total: { 
        $sum: 1 
      },
      active: {
        $sum: {
          $cond: [ { $eq: [ "$status", "active" ] }, 1, 0 ]
        }
      },
      inactive: {
        $sum: {
          $cond: [ { $eq: [ "$status", "inactive" ] }, 1, 0 ]
        }
      },
      deleted: {
        $sum: {
          $cond: [ { $eq: [ "$status", "deleted" ] }, 1, 0 ]
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id.name",
      city: "$_id.city",
      total: "$total",
      active: "$active",
      inactive: "$inactive",
      deleted: "$deleted"
    }
  }
])

【讨论】:

  • 在分组目标中出色地使用$cond
猜你喜欢
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 2021-03-19
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多