仅更新 MongoDB 中的某些子文档

问题描述 投票:0回答:1

给定这样的文件

{
  _id: '123456',
  items: [{
     itemId: 'abcd',
     qty: 1
  }, {
     itemId: 'defg',
     qty: 3 
  }]
}

我只想只更新某些项目;例如,我只想将 itemId = 'abcd'

 的数量增加 
5
,这样生成的文档就会变成

{ _id: '123456', items: [{ itemId: 'abcd', qty: 6 }, { itemId: 'defg', qty: 3 }] }

我该怎么做?

javascript mongodb meteor
1个回答
2
投票
基本上有3个步骤:

    从项目数组中选择
  1. itemid
    ,其中值为abcd
  2. 使用
  3. $inc
     属性来递增
  4. 使用
  5. $
     运算符(位置更新)来指定您想要的
从要更新的文档中增加 qty 键。

PFB最终查询:

db.schools.update({ items.itemId: 'abcd' },{ $inc : { items.$.qty : 5 } });
    
© www.soinside.com 2019 - 2024. All rights reserved.