moaningalways
moaningalways

Reputation: 461

mongodb append to an existing object

here is my document, and I want to add a new field to it:

{ 
email_address: '[email protected]', 
password: 'random_password',
first_name: 'John',
last_name: 'Doe',
website: {
    main_title: 'My Blog Website',
    main_url: 'http://www.example.com'
    }
}

currently i am doing:

db.test.update({"email_address": "[email protected]"},
{$set: {"website" : {"registrar": "namecheap"}}})

this erases the other fields inside website and just adds this new registrar field. how can I append to it?

Upvotes: 2

Views: 4642

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

You need to use dot-notation to set value to particular field of the sub-document, instead of setting the whole sub-document:

db.test.update(
    { "email_address": "[email protected]" },
    { $set: { "website.registrar" : "namecheap" } }
)

Upvotes: 13

Related Questions