在mongodb中同时减less很多数值

我有一个代表机器人的藏品,在位置插槽中持有产品库存,这些库存会增加和减less。

{ _id: "someid", name: "", inventory: [{ productId: "productId1", count: 30 }, { productId: "productId2", count: 56 }, { // ... up to 55 slots. }] } 

然后我有一个API将与PUT请求上的这个文档进行交互。 请求数据将包含要更新的inventory索引以及将其减less的数量,例如:

 [ { "inventory": 3, "inc": -10 }, // remove 10 from robot.inventory[3] { "inventory": 54, "inc": -2 }, // remove 2 from robot.inventory[10] ] 

我有以下代码。

 // robots submit to this api to keep their products up to date MachineApiV1.addRoute('/products', { authRequired: true, roleRequired: 'machine' }, { put: function () { // omit process to get data from above var user = Users.findOne(this.request.headers['x-user-id']); Robots.update(user.profiles.robot, { $inc: { } // this is where I am lost. }); } }); 

我不能完全想到在一次更新中做到这一点的方法。 如何在mongo文档中增加多个任意索引?

MongoDB使它非常简单 – 只需指定要更新的子文档数组中的位置即可:

 Robots.update(user.profiles.robot, { $inc: { 'inventory.3.count': -10, 'inventory.54.count': -2 } });