MongoDB 聚合和查找

MongoDB aggregation and lookup

我做了以下查询:

db.employees.aggregate([
  {
    $match: {
      isActive: true,
      
    }
  },
  {
    $lookup: {
      from: "shifts",
      localField: "_id",
      foreignField: "employee",
      as: "shifts"
    }
  },
  {
    $unwind: {
      path: "$shifts",
      preserveNullAndEmptyArrays: true,
      
    }
  }
])

现在得到以下结果:

[
    {
        "_id": "621eedae92979fd8f0e9451d",
        "name": "Pallab Koley",
        "shifts": {
            "_id": "62636b9fcbda6d2b17f5cae0",
            "month": "2022-05",
            "shift": [
                {
                    "date": "2022-05-01",
                    "shiftId": "622bb0f4b88dc92e3c2cac56"
                }
            ]
        }
    },
    {
        "_id": "621eedae92979fd8f0e9451d",
        "name": "Pallab Koley",
        "shifts": {
            "_id": "62636bb3cbda6d2b17f5cae2",
            "month": "2022-04",
            "shift": [
                {
                    "date": "2022-04-01",
                    "shiftId": "622bb0f4b88dc92e3c2cac56"
                }
            ]
        }
    },
    {
        "_id": "62626a7446ba9a911a623b37",
        "name": "Pinki Das",
        "shifts": {
            "_id": "62636ba4cbda6d2b17f5cae1",
            "month": "2022-05",
            "shift": [
                {
                    "date": "2022-05-01",
                    "shiftId": "622bb0f4b88dc92e3c2cac56"
                }
            ]
        }
    }
]

我需要用我添加的特定月份过滤数据

{
    $unwind: {
        path: '$shifts',
        preserveNullAndEmptyArrays: true,
    }
},
{
    $match: {
        "shifts.month": “2022-04”
    }
},

我得到的结果是:

[
    {
        "_id": "621eedae92979fd8f0e9451d",
        "name": "Pallab Koley",
        "shifts": {
            "_id": "62636bb3cbda6d2b17f5cae2",
            "month": "2022-04",
            "shift": [
                {
                    "date": "2022-04-01",
                    "shiftId": "622bb0f4b88dc92e3c2cac56"
                }
            ]
        }
    }
]

但我的要求是我需要员工集合中的所有其他现有员工,即使在轮班集合中也没有记录。请帮助得到它。

可能这就是你需要的。

  1. $match阶段
  2. $lookup阶段
  3. 删除 $unwind阶段。
  4. $project 阶段 - 使用 $filter 运算符过滤 shifts 数组中的文档,其中 month2022-04.
db.collection.aggregate([
  // $match ,
  // $lookup,
  // Remove $unwind
  {
    $project: {
      id: 1,
      name: 1,
      shifts: {
        "$filter": {
          "input": "$shifts",
          "cond": {
            $eq: [
              "$$this.month",
              "2022-04"
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground