I currently have the following dataset:
{
'component_id':1,
'_locales':[
{
'url': 'dutch',
'locale': 'nl_NL'
}
] (etc)
}
If I want to update the row with the locale I would run something similar to:
db.components.update(
{'component_id': 1, '_locales.locale': 'nl_NL'},
{$set: {'_locales.$': {'url': 'new url','locale':'nl_NL'}},
true
);
This works fine untill the locale does not exists:
db.components.update(
{'component_id': 1, '_locales.locale': 'en_US'},
{$set: {'_locales.$': {'url': 'new url','locale':'en_US'}},
true
);
since there is a unique index on component_id this will throw an exception complaining about a duplicate key.
Is there a way to automatically add the new 'document' with a different locale and update it if it already exists? According to the documentation using the position operator will not work with 'upserting'.
See Question&Answers more detail:os