mongodb - 多组聚合
问题描述
在我的数据库中有两种类型的会话-“工作室”、“教室”。我想要工作室课程的数量和课堂课程的数量以及课堂课程中的科目数量和工作室课程中的科目数量。
例如数据:
[
{
"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}
}
解决方案
您可以通过将文档指定为分组键来执行此操作
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 }
推荐阅读
- symfony - 加载“App\Controller\StudentController”时找不到类“Symfony\Bundle\FrameworkBundle\Controller\Controller”
- java - Maven 安全 HTTPS 存储库和 JDK5
- sql - 在 Oracle 中使用 JOIN 功能时,我有一些关于何时在此代码中使用额外别名的问题
- c# - 实例化后是否可以更改对象的(继承的)类
- python - 这个错误“ValueError:如果从数据张量评估,你应该指定`steps`参数”的解决方案是什么?
- python - 输入关键字列表以在网站上搜索字段并将结果保存到外部 HTML 文件
- mysql - 归档 AWS RDS mysql 数据库
- c - 当 **p 已经声明时,*p 是什么意思
- css - 如何使用角度创建具有最大化和最小化功能的 div
- java - 在多个流中批量写入mongoDB时出错