How can I validate that each value in a1 has a field key in d1.field1 and based on the validation result update d1.field2.val2 in a single update query?
I want the document to be updated based on the following condition:
if all the values of a1 are included in the field1 keys then the value of of field2.val would be updated to Updated. a successful result would look like this:
Otherwise, no changes should be made to the document.
I’m using the latest version of MongoDB (6.0.0) and the latest version of motor driver (3.1.1).
I would also like the UpdateResult.modified_count to be 0 in case the condition wasn’t met, if possible.
@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:
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.
Thank you @turivishal, this is exactly what I needed.
I ended up using a for loop in python to prepare the second part of the filter query since the array a1 is dynamic but your query works just like I needed.