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.
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'}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With