Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
MongoDB - Is there a way to perform $set on a hash without overwriting existing/unreferenced key/values?

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use $mergeObjects.

db.collection.update({
  _id: "12345"
},
[
  {
    "$set": {
      hash_field: {
        $mergeObjects: [
          "$hash_field",
          {
            "key1": "value1",
            "key2": "value2"
          }
        ]
      }
    }
  }
])

mongoplayground

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!