首页 > 解决方案 > 使用同一文档中的字段减少 mongodb 中的字段

问题描述

我有一个商店产品的集合,其中每个文档都是与商店及其位置相关联的产品,以及该商店的产品数量。文档架构如下所示:

样本文件:

{
    product         : 'Mobile Phone',
    store           : 'Electronics Store',
    total_quantity  : 5,
    locations       : [ { id: 'loc1', quantity: 3 }, { id: 'loc2', quantity: 2 } ]
}

我希望能够通过位置 ID 从所有商店产品中删除一个位置,同时更新总量。

我知道我可以通过获取每个文档并更新它来做到这一点,但这需要查询等于具有该位置的产品数量。因此,我正在考虑尝试通过执行两个查询来实现这一目标:

这里的问题是我不知道如何实现第一步,或者它是否可能。任何其他建议都非常受欢迎。

标签: mongodbmongoosemongodb-query

解决方案


由于您可以在开始 MongoDB version >= 的操作中执行update-with-an-aggregation-pipeline,请尝试以下查询:.update()4.2

查询 1:total_quantity此查询通过从现有的中减去locations.quantity要删除的特定元素来 重新创建字段total_quantity。还重新创建locations没有需要删除的元素的数组。

db.collection.updateMany({'locations.id': 'loc1'},
  [
    { $addFields: { total_quantity: { $subtract: [ "$total_quantity", { $arrayElemAt: [ "$locations.quantity", { $indexOfArray: [ "$locations.id", "loc1" ] } ] } ] } } },
    { $addFields: { locations: { $filter: { input: "$locations", cond: { $ne: [ "$$this.id", "loc1" ] } } } } }
  ]
)

测试:在这里测试聚合管道:mongoplayground

查询 2:

此查询首先重新创建locations没有需要删除的元素的数组,然后遍历剩余数组locations.quantity以汇总数组quantity中所有元素的所有值locations以创建total_quantity字段。

db.collection.updateMany({'locations.id': 'loc1'},
  [
    { $addFields: { locations: { $filter: { input: "$locations", cond: { $ne: [ "$$this.id", "loc1" ] } } } } },
    { $addFields: { total_quantity: { $reduce: { input: "$locations.quantity", initialValue: 0, in: { $add: [ "$$value", "$$this" ] } } } } }
  ]
)

测试:在这里测试聚合管道:mongoplayground

注意:如果您在执行这些查询时发现任何问题,请.updateMany()尝试.update()使用选项{ multi : true }


推荐阅读