MongoDB中精確元素數組中的更新字段我有一個這樣的文檔:{
_id:"43434",
heroes : [
{ nickname : "test", items : ["", "", ""] },
{ nickname : "test2", items : ["", "", ""] },
]}我能$set類的第二個元素。items數組中嵌入對象的數組。heros帶著nickname "test" ?結果:{
_id:"43434",
heroes : [
{ nickname : "test", items : ["", "new_value", ""] }, // modified here
{ nickname : "test2", items : ["", "", ""] },
]}
3 回答

白豬掌柜的
TA貢獻1893條經驗 獲得超10個贊
{"heros.nickname": "test"}
{"heros.$ // <- the dollar represents the first matching array key index
> db.denis.insert({_id:"43434", heros : [{ nickname : "test", items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]}); > db.denis.update( {"heros.nickname": "test"}, {$set: { "heros.$.items.1": "new_value" }})> db.denis.find(){ "_id" : "43434", "heros" : [ {"nickname" : "test", "items" : ["", "new_value", "" ]}, {"nickname" : "test2", "items" : ["", "", "" ]} ]}

楊魅力
TA貢獻1811條經驗 獲得超6個贊
db.collection.update({heroes:{$elemMatch:{ "nickname" : "test"}}}, { $push: { 'heroes.$.items': { $each: ["new_value" ], $position: 1 } } })
- 3 回答
- 0 關注
- 3215 瀏覽
添加回答
舉報
0/150
提交
取消