【问题标题】:Find all the tasks assigned to a member inside assignedTo array在assignedTo数组中查找分配给成员的所有任务
【发布时间】:2022-02-07 19:27:15
【问题描述】:
[
 {
  _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 聚合来返回分配给用户的所有任务并按状态对它们进行分组。例如,输入是: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: []
    }, 
  ]
}


【问题讨论】:

    标签: node.js mongodb aggregate


    【解决方案1】:

    您可以按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
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多