reptilicus
reptilicus

Reputation: 10417

Mongodb: updating fields in embedded document

If I have a document that looks like this:

{ 
    "_id" : 1, 
    "name": "Homer J. Simpson", 
    "income" : 45000,
    "address": { 
        "street": "742 Evergreen Terrace", 
        "city": "Springfield", 
        "state": "???", 
        "email": "[email protected]", 
        "zipcode": "12345", 
        "country": "USA"
     }
}

And want to do an update on some of the fields in the address document (leaving the other ones unchanged), and insert new fields if they do not already exist, such as this:

{ 
    "address": {
        "email": "[email protected]", 
        "zipcode": "77788", 
        "latitude" : 23.43545, 
        "longitude" : 123.45553
    }
}

Is there a way to do an atomic update all at once, or do you need to loop over the key/values in the new data and do a .update() for each one?

Upvotes: 0

Views: 677

Answers (2)

titogeo
titogeo

Reputation: 2184

As Sergio metioned use a $set.

{address.latitude : "77788"}

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312139

Use dot notation with a $set to target multiple embedded fields in a single update:

{ "$set": {
    "address.email": "[email protected]", 
    "address.zipcode": "77788", 
    "address.latitude" : 23.43545, 
    "address.longitude" : 123.45553
} }

Upvotes: 1

Related Questions