mongodb - 使用同一文档中的字段减少 mongodb 中的字段
问题描述
我有一个商店产品的集合,其中每个文档都是与商店及其位置相关联的产品,以及该商店的产品数量。文档架构如下所示:
样本文件:
{
product : 'Mobile Phone',
store : 'Electronics Store',
total_quantity : 5,
locations : [ { id: 'loc1', quantity: 3 }, { id: 'loc2', quantity: 2 } ]
}
我希望能够通过位置 ID 从所有商店产品中删除一个位置,同时更新总量。
我知道我可以通过获取每个文档并更新它来做到这一点,但这需要查询等于具有该位置的产品数量。因此,我正在考虑尝试通过执行两个查询来实现这一目标:
- 更新查询匹配位置 id 并根据它一次性减少总量
- 从位置数组中提取位置的删除查询
这里的问题是我不知道如何实现第一步,或者它是否可能。任何其他建议都非常受欢迎。
解决方案
由于您可以在开始 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 }
。
推荐阅读
- php - 网址重写形式
- ruby-on-rails - Rails 和 Kaminari -- 如何消除页间隙 [...]?
- php - 使用 PHP 将用户名设为大写
- variables - laravel 5.2 视图中的“未定义变量:a”
- java - Java Array split() 显示所有值但给出 arrayindexoutofbound 异常错误
- reactjs - 使用 Swagger 跨 IIS Express 管理微服务架构
- php - 从数据库中的laravel自动完成
- php - 在php中反向读取xml文件
- c++ - 如何解析这个条件?
- spring-boot - 支持 http 和 https