1

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 }
  }
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.