实际上,我想更新我的文档数组中具有viewProfile : true
的特定对象,但是它将更新数组中的所有元素
这是我的查询:
const user = await User.updateMany(
{
_id: req.userData.id,
"notifications.viewProfile" : true
},
{
$set: {
"notifications.$[].read": false
}
}
);
考虑本文档
/* 1 */
{
"_id" : ObjectId("5e4ae76bd4e24418a020b665"),
"username" : "test",
"notifications" : [
{
"createdAt" : ISODate("2020-02-18T19:22:24.809Z"),
"_id" : ObjectId("5e4c397075265a36203dab5a"),
"message" : "testone is now following you.",
"viewProfile" : false,
"read" : false
},
{
"createdAt" : ISODate("2020-02-18T19:22:29.200Z"),
"_id" : ObjectId("5e4c397575265a36203dab5d"),
"message" : "testone is now following you.",
"viewProfile" : true,
"read" : false
}
],
}
答案 0 :(得分:0)
使用过滤后的位置运算符$[<identifier>]
。参考https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
const user = await User.update(
{
_id: req.userData.id
},
{ $set: { "notifications.$[element].read": false } },
{
multi: true,
arrayFilters: [ { "element.viewProfile": true } ]
}
)