Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating embedded document in MongoDB

My documents are structured as follows:

{_id: 1, country: 'USA', names: [{language: 'en', name: 'New York', state:'new'}, {language: 'es', name: 'Nueva York', state:'translated'}]}
{_id: 2, country: 'France', names: [{language: 'en', name: 'Paris', state:'new'}, {language: 'it', name: 'Parigi', state:'translated'}]}
...

I want to update the state of an item for a specific language, and if the language does not exist, to add the corresponding embedded document. For example, I would want to update item 1 to set state='new' for language='es' because that language exists:

{_id: 1, country: 'USA', names: [{language: 'en', name: 'New York', state:'new'}, {language: 'es', name: 'Nueva York', state:'translated'}]}

And I would want to add an embedded document to item 2 with state='new' and language='fr' because it doesn't exist:

{_id: 2, country: 'France', names: [{language: 'en', name: 'Paris', state:'new'}, {language: 'it', name: 'Parigi', state:'translated'}, {language: 'fr', name: 'Paris', state:'new'}]}

How can I do that?

Thanks.

like image 406
alste Avatar asked Nov 05 '22 10:11

alste


1 Answers

You need to use The $ positional operator. See http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator for more.

In your case it will be

db.cities.update({'_id':1,'names.language':'es'},{$set:{'names.$.state':'new'}});
like image 146
Samyak Bhuta Avatar answered Nov 10 '22 07:11

Samyak Bhuta