亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MongoDB中精確元素數組中的更新字段

MongoDB中精確元素數組中的更新字段

汪汪一只貓 2019-07-04 16:33:11
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個贊

您需要使用兩個概念:MongoDB位置算子并簡單地為要更新的條目使用數字索引。

位置運算符允許您使用如下條件:

{"heros.nickname": "test"}

然后引用已找到的數組條目,如下所示:

{"heros.$  // <- the dollar represents the first matching array key index

因為您想要更新“Item”中的第二個數組條目,而數組鍵是0索引-這是鍵1。

因此:

> 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" : ["", "", "" ]}
    ]}


查看完整回答
反對 回復 2019-07-04
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

db.collection.update({heroes:{$elemMatch:{ "nickname" : "test"}}},
 {
     $push: {
        'heroes.$.items': {
           $each: ["new_value" ],
           $position: 1
        }
     }
   })


查看完整回答
反對 回復 2019-07-04
  • 3 回答
  • 0 關注
  • 3215 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號