2015-02-24 59 views
1

我想增加數據庫中找到的文檔的子文檔中元素的數量。如何用JavaScript在mongodb中增加文檔的子文檔中的值

我找到文檔工作:

Cart.findOne({_id: '2JKD6eynaYmTGnbiZ',"items.productId": 'inkGTN7T89fqwEqTB' }); 

返回此:

{ _id: '2JKD6eynaYmTGnbiZ', 

    items: 

    [ { _id: 'LYKPShnDDfYHS8zmx', 

     productId: 'inkGTN7T89fqwEqTB', 

     quantity: 1 } ], 

    sessionId: 'jhizTjhiErYRNKhJW’ } 

但我似乎無法增加子文件與本次更新的項目中的一個元素的qty

Cart.update({ 
    _id: '2JKD6eynaYmTGnbiZ’, "items.productId": ‘inkGTN7T89fqwEqTB' 
}, { 
    $set: { 
     updatedAt: new Date() 
    }, 
    $inc: { 
     "items.quantity": 10 
    } 
}); 

我不知道我是否引用它錯誤,我試圖使用items.$.productId來引用該元素,但不會在查找中返回文檔。

+0

我認爲你需要調用爲$的新字段設置和更新的領域,並添加{upsert:true},我不確定$ inc是做什麼的。請參閱http://docs.mongodb.org/manual/tutorial/modify-documents/ – faljbour 2015-02-24 02:10:24

回答

1

您需要使用表示匹配items數組元素在你的$inc該指數$ positional operator

Cart.update(
{ 
    _id: '2JKD6eynaYmTGnbiZ', "items.productId": 'inkGTN7T89fqwEqTB' 
}, { 
    $set: { 
     updatedAt: new Date() 
    }, 
    $inc: { 
     "items.$.quantity": 10 
    } 
});