Updating an 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 element for a specific language, and if the language does not exist, add the corresponding embedded document. For example, I would like to update element 1 to set state='new' for language='es' , because this language exists:

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

And I would like to add an inline document to element 2 with state='new' and language='fr' , because it does not 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 this?

Thanks.

+4
source share
1 answer

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

In your case it will be

 db.cities.update({'_id':1,'names.language':'es'},{$set:{'names.$.state':'new'}}); 
+1
source

Source: https://habr.com/ru/post/1384837/


All Articles