Home > Back-end >  How do I update a nested object in mongo only if that property exists?
How do I update a nested object in mongo only if that property exists?

Time:11-11

With a collection like:

{
_id: 1,
obj: {val1: 1, val3: 3}
},
{
_id: 2,
obj: {val2: 2, val3: 3}
}

can I update only the existing values in the obj in on query like

col.updateMany({ _id: { $in: [1, 2] } }, { $set: { val1: 12, val2: 22, val3: 32 } })

but I want the result to be

{
_id: 1
obj: {val1: 12, val3: 32 }
},
{
_id: 2
obj: {val2: 22, val3: 32}
}

I guess I am looking for a $setIfExists option.

Thank you

CodePudding user response:

Query

  • you can use a pipeline update to do a conditional update, requires MongoDB >=4.2
  • instead of 12,22,32 put any values for val1,val2,val3
  • it checks first if the value exists, and if exists update it with new value, else $REMOVE (it means add remove = add nothing)

Test code here

update(
{"_id": {"$in": [1,2]}},
[{"$set": 
  {"obj.val1": 
   {"$cond": 
    [{"$ne": [{"$type": "$obj.val1"}, "missing"]}, 12, "$$REMOVE"]},
   "obj.val2": 
    {"$cond": 
     [{"$ne": [{"$type": "$obj.val2"}, "missing"]}, 22, "$$REMOVE"]},
    "obj.val3": 
     {"$cond": 
      [{"$ne": [{"$type": "$obj.val3"}, "missing"]}, 32, "$$REMOVE"]}}}],
{"multi": true})
  • Related