假設我想更新檔案陣列的物件值,但首先我需要先查找它的 id,這是檔案的結構
{
_id: ObjectId('12312')
notifications: [
{
_id: ObjectId('1')
status: 'unread'
},
{
_id: ObjectId('2')
status: 'unread'
},
{
_id: ObjectId('3')
status: 'unread'
}
]
}
我想更新該用戶下的通知狀態,其中 objectId 必須等于結果陣列內
result =
[
new ObjectId("1"),
new ObjectId("2"),
]
這應該在更新后產生這個結果
{
_id: ObjectId('12312')
notifications: [
{
_id: ObjectId('1')
status: 'read'
},
{
_id: ObjectId('2')
status: 'read'
},
{
_id: ObjectId('3')
status: 'unread'
}
]
}
這是我到目前為止所做的,但我沒有得到我需要的結果
const updateuser = await User.updateMany({_id:idofuser, "notifications._id": { $in : result }},{
$set: {
"notifications.$.status": "read",
}
})
uj5u.com熱心網友回復:
您可以使用$map
來迭代notifications
和使用$cond
并$mergeObjects
執行條件更新。
db.collection.update({
"_id": "12312"
},
[
{
"$set": {
"notifications": {
"$map": {
"input": "$notifications",
"as": "n",
"in": {
"$cond": {
"if": {
"$in": [
"$$n._id",
[
"1",
"2"
]
]
},
"then": {
"$mergeObjects": [
"$$n",
{
"status": "read"
}
]
},
"else": "$$n"
}
}
}
}
}
}
],
{
multi: true
})
這是Mongo Playground供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/492067.html
標籤:javascript 数组 mongodb mongodb查询 聚合框架