试图在多个字段上聚合

时间:2018-10-25 12:23:28

标签: mongodb mongoose aggregation-framework aggregate

我创建了一个时间输入系统,用户可以输入给定时间段内完成一项任务所花费的时间(百分比)。每条记录如下所示。我将用户_id更改为显式名称,以使其更易于可视化

"project_name": "first_project",
"linked_project": "5bd057f5d4b8173d88b7fe47",
"percentage": 25,
"user": {
    "$oid": "Steve"
},

"project_name": "first_project",
"linked_project": "5bd057f5d4b8173d88b7fe47",
"percentage": 50,
"user": {
    "$oid": "Steve"
},

"project_name": "second_project",
"linked_project": "5bd057f5d4b8173d88b7fe48",
"percentage": 25,
"user": {
    "$oid": "Steve"
},

"project_name": "second_project",
"linked_project": "5bd057f5d4b8173d88b7fe48",
"percentage": 75,
"user": {
    "$oid": "Mary"
},

我正在尝试先按人员分组,然后按项目分组。基本上,我希望每个用户总共花在特定任务上的费用总计。不知道我想要达到的目标是否可能。我在下面列出了我要实现的目标:

示例输出:

[
    {
        user: Steve,
        projects: [
            first_project: 75,
            second_project: 25
        ]
    },
    {
        user: Mary,
        projects: [
            second_project: 75
        ]
    }

]

我已经尝试了多种方法来实现这一目标,但距离目标还差得很远。希望有人对如何实现这一目标有所了解。

1 个答案:

答案 0 :(得分:1)

您可以使用多个组,一组用于为每个用户和project_name组合求和,第二组为用户推送所有文档。

db.colname.aggregate([
  {"$group":{
    "_id":{
      "user":"$user",
      "project_name":"$project_name"
    },
    "time":{"$sum":"$percentage"}
  }},
  {"$group":{
    "_id":"$_id.user",
    "projects":{"$push":{"project_name":"$_id.project_name","time":"$time"}}
  }}
])

要以单个文档的形式获取输出,可以在最后一个小组阶段使用

"projects":{"$mergeObjects":{"$arrayToObject":[[["$_id.project_name","$time"]]]}}