简体   繁体   中英

mongodb pipeline aggregation group results into array

I have a projects collection:

{
  _id: 1,
  title: "Project 1"
},
{
  _id: 2,
  title: "Project 2"
}

and a (time) entries collection:

{
  _id: 90123,
  project_id: 1,
  task_id: 1,
  hours: 3
},
{
  _id: 90124,
  project_id: 1,
  task_id: 1,
  hours: 5
},
{
  _id: 90125,
  project_id: 2,
  task_id: 2,
  hours: 1
},
{
  _id: 90126,
  project_id: 1,
  task_id: 2,
  hours: 2
}

I'd like to use a pipeline aggregation to:

  • Get entries for project 1
  • Sum all entries for project 1 as "totalSpent"
  • Group by task_id with summed hours per task

Something like this as the end result:

{
  totalSpent: 10,
  spentByTask: {
    { task_id: 1, spent: 8 },
    { task_id: 2, spent: 2 }
  }
}

give this pipeline a try:

db.entries.aggregate(
    [
        {
            $match: { project_id: 1 }
        },
        {
            $group: {
                _id: '$task_id',
                spent: { $sum: '$hours' }
            }
        },
        {
            $group: {
                _id: null,
                totalSpent: { $sum: '$spent' },
                spentByTask: { $push: { task_id: '$_id', spent: '$spent' }
                }
            }
        },
        {
            $project: { _id: 0 }
        }
    ])

if you need a different result, let me know and i'll update my answer accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM