我通过引用相关的stackoverflow答案编译了2个update查询,但是,它似乎不起作用,query更新所有元素,而只更新与条件匹配的元素。
文件:
[
{
"_id": 259,
"members": [
{
"email": "test1@gmail.com",
"added_by": "javapedia.net",
"status": "pending"
},
{
"email": "test2@gmail.com",
"added_by": "javapedia.net",
"status": "pending"
},
{
"email": "test3@gmail.com",
"status": "pending"
}
]
}
]
查询1:使用elemMatch运算符,mongodb:
https://mongoplayground.net/p/4cNgWJse86W
db.collection.update({
_id: 259,
"members": {
"$elemMatch": {
"email": {
"$in": [
"test3@gmail.com",
"test4@gmail.com"
]
}
}
}
},
{
"$set": {
"members.$[].status": "active"
}
},
{
"multi": true
})
https://mongoplayground.net/p/tNu395B2RFx
db.collection.update({
_id: 259,
"members.email": {
"$in": [
"test3@gmail.com",
"test4@gmail.com"
]
}
},
{
"$set": {
"members.$[].status": "active"
}
},
{
"multi": true
})
预期结果:只有一个元素test3@gmail.com状态应更新为活动。
实际结果:两个查询都更新所有记录。