在MongoDB中更新嵌入式文档

我的文件结构如下:

{_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'}]}
...

我想更新特定语言的项目状态,如果该语言不存在,则添加相应的嵌入文档.例如,我想更新第1项,为language =’es’设置state =’new’,因为该语言存在:

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

我想在第2项中添加一个嵌入式文档,其中state =’new’和language =’fr’,因为它不存在:

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

我怎样才能做到这一点?

谢谢.

最佳答案 您需要使用$location运算符.有关更多信息,请参见
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

在你的情况下它将是

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