在MongoDB中更新嵌入式文档

时间:2011-12-06 05:12:04

标签: mongodb node.js

我的文件结构如下:

{_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项,为state='new'设置language='es',因为该语言存在:

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

我希望使用state='new'language='fr'向第2项添加嵌入式文档,因为它不存在:

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

我该怎么做?

感谢。

1 个答案:

答案 0 :(得分:2)

您需要使用$ position运算符。有关详情,请参阅http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

在你的情况下,它将是

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