I compiled 2 update queries by referring to related stackoverflow answers, however, it doesn't seem to work, query updates all elements while only elements matching the criteria are expected to update.
Document:
[
{
"_id": 259,
"members": [
{
"email": "[email protected]",
"added_by": "javapedia.net",
"status": "pending"
},
{
"email": "[email protected]",
"added_by": "javapedia.net",
"status": "pending"
},
{
"email": "[email protected]",
"status": "pending"
}
]
}
]
Query1: Using elemMatch operator, mongodb playground: https://mongoplayground.net/p/4cNgWJse86W
db.collection.update({
_id: 259,
"members": {
"$elemMatch": {
"email": {
"$in": [
"[email protected]",
"[email protected]"
]
}
}
}
},
{
"$set": {
"members.$[].status": "active"
}
},
{
"multi": true
})
Query2: using $in, mongodb playground : https://mongoplayground.net/p/tNu395B2RFx
db.collection.update({
_id: 259,
"members.email": {
"$in": [
"[email protected]",
"[email protected]"
]
}
},
{
"$set": {
"members.$[].status": "active"
}
},
{
"multi": true
})
Expected result: only one element with [email protected] status should be updated to active.
Actual result: both queries update all records.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…