首页 > 解决方案 > 多组聚合

问题描述

在我的数据库中有两种类型的会话-“工作室”、“教室”。我想要工作室课程的数量和课堂课程的数量以及课堂课程中的科目数量和工作室课程中的科目数量。

例如数据:

    [
  {
    "key": 1,
    "type": "studio",
    "sub": "english"
  },
  {
    "key": 2,
    "type": "studio",
    "sub": "history"
  },
  {
    "key": 3,
    "type": "classroom",
    "sub": "english"
  },
  {
    "key": 4,
    "type": "studio",
    "sub": "english"
  },
  {
    "key": 5,
    "type": "classroom",
    "sub": "english"
  },
  {
    "key": 5,
    "type": "classroom",
    "sub": "geography"
  }
]

这是我必须按会话类型分组的查询。

    db.collection.aggregate([
  {
    $group: {
      _id: "$type",
      groupedData: {
        $push: {
          key: "$key",
          "sub": "$sub",
          "type": "$type"
        }
      }
    }
  }
])

通过这个我得到

    [
  {
    "_id": "classroom",
    "groupedData": [
      {
        "key": 3,
        "sub": "english",
        "type": "classroom"
      },
      {
        "key": 5,
        "sub": "english",
        "type": "classroom"
      },
      {
        "key": 5,
        "sub": "geography",
        "type": "classroom"
      }
    ]
  },
  {
    "_id": "studio",
    "groupedData": [
      {
        "key": 1,
        "sub": "english",
        "type": "studio"
      },
      {
        "key": 2,
        "sub": "history",
        "type": "studio"
      },
      {
        "key": 4,
        "sub": "english",
        "type": "studio"
      }
    ]
  }
]

但我想要工作室和教室中的科目计数以及工作室和教室中的会话总数

例如。

{
  studio: { count: 3, englishInStudio: 2, historyInStudio: 1 },
  classroom: {count: 3, englishInClassroom: 2, geographyInClassroom: 1}
}

标签: mongodbmongoose

解决方案


您可以通过将文档指定为分组键来执行此操作

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

这将输出以下内容,这些内容会获取您所需的值,但格式不同:

{ "_id" : { "type" : "classroom", "sub" : "english" }, "count" : 2 }
{ "_id" : { "type" : "studio", "sub" : "history" }, "count" : 1 }
{ "_id" : { "type" : "classroom", "sub" : "geography" }, "count" : 1 }
{ "_id" : { "type" : "studio", "sub" : "english" }, "count" : 2 }

推荐阅读