猫鼬聚合返回整个对象而不是 1 个对象及其属性

Mongoose aggregate returning whole object instead of 1 object with its propertys

我的用户有一个“通知”字段,它是一个数组

我正在尝试获取尚未阅读的通知,因此我编写了此查询:

await User.aggregate([
        { $unwind: '$notifications' },
        { $match: { 'notifications.read': false } },
        { $project: { "notifications": 1 } }
    ])

我预计它会 return 类似于:

[
    {
        "_id": "6201a79305489c2ae98b2753",
        "notifications": [
            {
                "_id": "62473e2f76b38858303b41d8",
                "text": "A tarefa tarefa 2 foi atualizada pela sua equipe!",
                "read": false,
                "date": "2022-04-01T18:02:23.813Z"
            },
            {
                "_id": "62473c4776b38858303b41a6",
                "text": "A tarefa finalizei foi atualizada pela sua equipe!",
                "read": false,
                "date": "2022-04-01T17:54:15.142Z"
            },
            {
                "_id": "62473e2f76b38858303b41d9",
                "text": "A tarefa tarefa 2 foi atualizada pela sua equipe!",
                "read": false,
                "date": "2022-04-01T18:02:23.814Z"
            }
        }
    ]
]

但它 returned: [

    {
        "_id": "6201a79305489c2ae98b2753",
        "notifications": {
            "_id": "62473e2f76b38858303b41d8",
            "text": "A tarefa tarefa 2 foi atualizada pela sua equipe!",
            "read": false,
            "date": "2022-04-01T18:02:23.813Z"
        }
    },
    {
        "_id": "6227b07b04cd1196302dba06",
        "notifications": {
            "_id": "62473c4776b38858303b41a6",
            "text": "A tarefa finalizei foi atualizada pela sua equipe!",
            "read": false,
            "date": "2022-04-01T17:54:15.142Z"
        }
    },
    {
        "_id": "6227b07b04cd1196302dba06",
        "notifications": {
            "_id": "62473e2f76b38858303b41d9",
            "text": "A tarefa tarefa 2 foi atualizada pela sua equipe!",
            "read": false,
            "date": "2022-04-01T18:02:23.814Z"
        }
    }
]

如何在同一个数组中按 read:false 和 return 过滤我的用户通知?

我会像这样使用 $filter 来完成这项任务:

db.collection.aggregate([
 { $match: { 'notifications.read': false } },
 {
   "$addFields": {
    "notifications": {
      "$filter": {
        "input": "$notifications",
        "as": "n",
        "cond": {
         $eq: [
            "$$n.read",
             false
         ]
      }
     }
    }
   }
  }
])

解释:

  1. 匹配所有有通知的文档。read:false
  2. 仅过滤具有 read:false
  3. 的通知

playground