My User have a "notifications" field, that is an array
I'm trying to get it's notifications that haven't been read, so i've written this query:
await User.aggregate([
{ $unwind: '$notifications' },
{ $match: { 'notifications.read': false } },
{ $project: { "notifications": 1 } }
])
I've expected it to return something like:
[
{
"_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"
}
}
]
]
But it 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"
}
}
]
How can i filter my user notifications by read:false and return it in the same array?
CodePudding user response:
I would ratter use $filter for this task like this:
db.collection.aggregate([
{ $match: { 'notifications.read': false } },
{
"$addFields": {
"notifications": {
"$filter": {
"input": "$notifications",
"as": "n",
"cond": {
$eq: [
"$$n.read",
false
]
}
}
}
}
}
])
Explained:
- match all documents having notifications.read:false
- filter only notifications that have the read:false