Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Find all the tasks assigned to a member inside assignedTo array
[
 {
  _id: 1,
  title: "Task 1",
  assignedTo: ["userId1", "userId2", "userId3"]
  status: "To do"
 },
 {
  _id: 2,
  title: "Task 2",
  assignedTo: ["userId1", "userId2"],
  status: "In progress"
 },
 {
  _id: 3,
  title: "Task 3",
  assignedTo: ["userId3"],
  status: "Completed"
 }
]

I want to use MongoDB aggregate to return all the tasks assigned to a user and group them by status. For example, the input is: userId: "userId1" , and the expected output should be something like this:

{
  results: [
    {
      status: "To do",
      tasks: [
          {
            _id: 1,
            title: "Task 1",
            assignedTo: ["userId1", "userId2", "userId3"]
           }
         ]
    }, 
    {
      status: "In progress",
      tasks: [
          {
            _id: 2,
            title: "Task 2",
            assignedTo: ["userId1", "userId2"]
           }
         ]
    }, 
    {
      status: "Completed",
      tasks: []
    }, 
  ]
}


over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you can group by status and push items if it matches the userId1

you can test it here mongodb playground

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        status: "$status"
      },
      tasks: {
        "$push": {
          $cond: [
            {
              "$in": [
                "userId1",
                "$assignedTo"
              ]
            },
            {
              _id: "$_id",
              title: "$title",
              assignedTo: "$assignedTo"
            },
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    "$project": {
      status: "$_id.status",
      tasks: 1,
      _id: 0
    }
  }
])
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!