Let's say I have a document like this:
{
_id: "12345",
hash_field: {
"foo": "bar"
}
}
And at some point, without knowing what the value of this document's hash_field is, I need to add some more key/value pairs to it while leaving the current intact. I'm looking for a way to do this without wiping the existing data, and without having to make multiple nested updates
db.myCollection.updateOne({_id:"12345"},
{'$set': {
hash_field: {
"key1": "value1",
"key2": "value2"
}
}
})
The above will wipe the {"foo":"bar"}.
I know I can do two separate $set calls with '$set': {"hash_field.key1": "value1"} and '$set': {"hash_field.key2": "value2"} but I'm looking for a way to do this in one mongo update. Possible?
Use $mergeObjects.
db.collection.update({
_id: "12345"
},
[
{
"$set": {
hash_field: {
$mergeObjects: [
"$hash_field",
{
"key1": "value1",
"key2": "value2"
}
]
}
}
}
])