2011-11-07 124 views
6

更新嵌入式文件我有以下文件:MongoDB的:如何在陣列

{_id: '4eb79ee1e60fc603788e7259', 
Name: 'name', 
Subsidiaries: [ 
    { _id: '4eb79eeae60fc603788e7271', 
    Location: 'location1'}, 
    { _id: 'subid2', 
    Location: 'location2'}, 
]} 

我想更新子公司的位置:

db.Departments.update({ "_id" : ObjectId("4eb79ee1e60fc603788e7259"), "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, { "$set" : { "Subsidiaries.Location" : "City" } }) 

但是MongoDB中返回一個錯誤:「不能追加使用字符串字段名稱[位置]「

回答

15

您必須使用$ poistional operator來更新嵌入式文檔,

db.Departments.update(
    { "_id" : ObjectId("4eb79ee1e60fc603788e7259"), 
     "Subsidiaries._id" : ObjectId("4eb79eeae60fc603788e7271") }, 
    { "$set" : { "Subsidiaries.$.Location" : "City" } } 
) 
+4

在我的情況下,這就是說, **不能追加到使用字符串字段名稱[$] ** 的數組,雖然我可以看到上面的文檔和我的文檔完全相同。 –