【发布时间】:2015-06-05 21:18:38
【问题描述】:
给定以下数据集:
[
{
"account_id" : "1111"
"task_id" : "aaaa",
"workweek" : "20",
"hours": "18"
},
{
"account_id" : "1111"
"task_id" : "aaaa",
"workweek" : "20",
"hours": "12"
},
{
"account_id" : "1111"
"task_id" : "aaaa",
"workweek" : "21",
"hours": "10"
},
{
"account_id" : "1111"
"task_id" : "bbbb",
"workweek" : "21",
"hours": "5"
},
{
"account_id" : "2222"
"task_id" : "cccc",
"workweek" : "21",
"hours": "15"
}
]
我想对文档进行分组,并获得以下格式的结果:
[
{
"account_id": "1111",
"tasks": [
{
"task_id": "aaaa",
"workweeks": [
{
"workweek": "20",
"total_hours": "30"
},
{
"workweek": "21",
"total_hours": "10"
}
]
},
{
"task_id": "bbbb",
"workweeks": [
{
"workweek": "21",
"total_hours": "5"
}
]
}
]
},
{
"account_id": "2222",
"tasks": [
{
"task_id": "cccc",
"workweeks": [
{
"workweek": "21",
"total_hours": "15"
}
]
},
]
}
]
我损坏的聚合代码如下:
db.tasks.aggregate([
{"$group": {
"_id": {
"account_id": "$account_id",
"task_id": "$task_id",
"workweek": "$workweek",
},
"total_hours": {$sum: "$hours"}
}},
{"$group": {
"_id": "$_id.account_id",
"tasks": {
"$push": {
"task_id": "$_id.task_id",
"workweeks": {
"$push": {
"workweek": "$_id.workweek",
"total_hours": "$total_hours"
}
}
}
}
}}
]);
我收到此错误: "errmsg" : "异常:无效的运算符 '$push'", 我认为这是因为每个 $group 块我只能 $push 一次。
关于如何达到预期结果的任何想法?
【问题讨论】:
标签: mongodb aggregation-framework