在 assignedTo 数组中查找分配给成员的所有任务

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

我想使用 MongoDB 汇总到 return 分配给用户的所有任务,并按状态对它们进行分组。例如,输入是:userId: "userId1" ,预期的输出应该是这样的:

{
  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: []
    }, 
  ]
}


您可以按 status 分组并推送符合 userId1

的项目

你可以在这里测试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
    }
  }
])