2016-06-15 106 views
1

我有如下所示的mongodb文檔。MongoDB向子文檔添加新字段

{ 
    "_id" : ObjectId("57616e718ed5a017089143f2"), 
    "subitems" : { 
     "1" : "a", 
     "2" : "b" 
    } 
} 

我試圖添加新的字段到「子項目」字段。

db.items.update({ "_id" : ObjectId("57616e718ed5a017089143f2") }, { $set: { subitems: { 3: "c" } } }) 

,而不是更新的領域,其覆蓋它就像

{ 
    "_id" : ObjectId("57616e718ed5a017089143f2"), 
    "subitems" : { 
     "3" : "c" 
    } 
} 

我如何實現結果

{ 
    "_id" : ObjectId("57616e718ed5a017089143f2"), 
    "subitems" : { 
     "1" : "a", 
     "2" : "b", 
     "3" : "c" 
    } 
} 
+2

只是好奇,爲什麼有一個字符串的整數字段的名稱? – styvane

+0

@ user3100115它只是一個虛擬數據,原始文檔沒有整數字符串作爲字段的名稱 – sravis

回答

1

使用dot notation到字段添加到嵌入文檔:

db.items.update(
    { "_id" : ObjectId("57616e718ed5a017089143f2") }, 
    { "$set": { "subitems.3": "c" } } 
) 

更多來自documentation