How to give multiple conditions in MongoDB updateMany query?

Considering the below documents in a db, i want to update every document with a new key "new_feature" and set its value as "1" only if any one of the value of the keys "old_feature_1" and "old_feature_2" is "1" and at the same time i want to remove the fields "old_feature_1" and "old_feature_2" from the document and for other documents which has both the old_feature values as "0", we just have to remove those fields and add "new_feature" with value as "0". below is the schema where "preferences" refers to a collection.

"preferences"  {
     {
       "old_feature_1":"1",
       "old_feature_2":"0"
    },
    {
       "old_feature_1":"0",
       "old_feature_2":"0"
    },
    {
       "old_feature_1":"1",
       "old_feature_2":"1"
    }
}

I tried the below query but it will update only those records whose old_feature values are "0".

db.preferences.updateMany({"new_feature":{$exists:false},"old_feature_1":'0',"old_feature_2":'0'}
{$unset:{"old_feature_1":'0',"old_feature_2":'0'},
    $set:{"new_feature":"1"}})

Expected result is

"preferences" : {
     {
       "new_feature":"1"
    },
    {
       "new_feature":"0"
    },
    {
       "new_feature":"1"
    }
}


Read more here: https://stackoverflow.com/questions/67387010/how-to-give-multiple-conditions-in-mongodb-updatemany-query

Content Attribution

This content was originally published by Srii at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: