【问题标题】:How to increment a value within a subdocument of a document in mongodb with JavaScript如何使用 JavaScript 在 mongodb 文档的子文档中增加一个值
【发布时间】:2015-02-24 01:36:35
【问题描述】:

我想增加在数据库中找到的文档的子文档中元素的数量。

我在文件上的发现有效:

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

返回这个:

{ _id: '2JKD6eynaYmTGnbiZ',

  items: 

   [ { _id: 'LYKPShnDDfYHS8zmx',

       productId: 'inkGTN7T89fqwEqTB',

       quantity: 1 } ],

  sessionId: 'jhizTjhiErYRNKhJW’ }

但我似乎无法通过此更新增加 items 子文档中元素的 qty

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

我不知道我是否引用错了,我尝试使用items.$.productId 来引用该元素,但在查找时什至不会返回文档。

【问题讨论】:

标签: javascript mongodb meteor database


【解决方案1】:

您需要在$inc 中使用代表匹配的items 数组元素的索引的$ positional operator

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

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2014-07-29
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多