@loay_khateeb The relevant issue is to validate each value in a1 against the keys in d1.field1 and update d1.field2.val2 based on the validation result in a single update query. The provided query is not working, so an alternative solution is needed.
One solution can be to iterate over the values in a1 and check if they exist as keys in d1.field1. Then, based on the validation result, update d1.field2.val2. This can be achieved using the following query:
db.coll.updateOne(
{ "_id": ObjectId("640b0e3629cb7001946137a3") },
[
{
"$addFields": {
"temp_f1": { "$objectToArray": "$field1" }
}
},
{
"$set": {
"field2.val": {
"$cond": [
{
"$allElementsTrue": {
"$map": {
"input": ["attr1", "attr2", "attr3"],
"in": {
"$in": [
"$$this",
"$temp_f1.k"
]
}
}
}
},
"UPDATED!",
""
]
}
}
},
{
"$unset": "temp_f1"
}
]
)
The query first uses $objectToArray to convert field1 into an array of key-value pairs. Then, it creates a new field field2.val using $cond that checks if all elements in a1 are present in temp_f1.k, which is an array of keys in field1. If the condition is true, it sets the value of field2.val to "UPDATED!", otherwise, it sets it to an empty string. Finally, it uses $unset to remove the temp_f1 field.
le me know if this worked ?