我的用戶有一個“通知”欄位,即一個陣列
我正在嘗試獲取尚未閱讀的通知,因此我撰寫了以下查詢:
await User.aggregate([
{ $unwind: '$notifications' },
{ $match: { 'notifications.read': false } },
{ $project: { "notifications": 1 } }
])
我預計它會回傳如下內容:
[
{
"_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"
}
}
]
]
但它回傳:[
{
"_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 過濾我的用戶通知并將其回傳到同一個陣列中?
uj5u.com熱心網友回復:
我會像這樣使用 $filter 來完成這個任務:
db.collection.aggregate([
{ $match: { 'notifications.read': false } },
{
"$addFields": {
"notifications": {
"$filter": {
"input": "$notifications",
"as": "n",
"cond": {
$eq: [
"$$n.read",
false
]
}
}
}
}
}
])
解釋:
- 匹配所有具有通知的檔案。讀取:假
- 僅過濾具有 read:false 的通知
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455113.html
上一篇:我想找到一個四舍五入的方程的值
