I have a collection like this:
[
{
"key": 1,
"form_details": {
"PROJECT": "RD",
"INTERESTING": true
}
},
{
"key": 2,
"form_details": {
"PROJECT": "RC",
"INTERESTING": true
}
}
]
I would update the embedded field “form_details.INTERESTING” to false if “form_details.PROJECT” is “RD”, and maintain current value elseware.
I found this solution:
db.collection.update({},
{
$set: {
"form_details.INTERESTING": {
$cond: {
if: {
$eq: [
"$form_details.PROJECT",
"RD"
]
},
then: false,
else: "$form_details.INTERESTING"
}
}
}
})
But it works wrong, updating all the value under $cond as an Object if condition is met:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"form_details": {
"INTERESTING": {
"$cond": {
"else": "$form_details.INTERESTING",
"if": {
"$eq": [
"$form_details.PROJECT",
"RD"
]
},
"then": false
}
},
"PROJECT": "RD"
},
"key": 1
},
{
"_id": ObjectId("5a934e000102030405000001"),
"form_details": {
"INTERESTING": true,
"PROJECT": "RC"
},
"key": 2
}
]
I would simply update it to “false” value if that condition is met.
Here is the example playground:
https://mongoplayground.net/p/d1uSCHxvwAm