mongodb - MongoDB - $ lte 2个键在同一个对象中相互对抗
问题描述
样本数据:
let arrObj = [
{
"id": 9999,
"arrObj": [
{
"name": "xyz",
"arrId": 1,
"total1": 54,
"total2": 55
},
{
"type": "abc",
"arrId": 2,
"total1": 35,
"total2": 32
}
]
}
]
寻找 mongo 更新,如:
db.coll('collectionName').update({
id: 9999,
arrObj.arrId: 1,
arrObj.total1 : {$lte : arrObj.total2}
},{$inc : {total2 : 1}})
我需要匹配 2 个字段,并基于它增加一个字段值。提前致谢。
解决方案
从 MongoDB v4.2 开始,您可以将更新与聚合管道一起使用,
$map
,如果找到匹配项,请检查您的条件,然后添加一个total2
db.coll('collectionName').update(
{ id: 9999 },
[{
$set: {
arrObj: {
$map: {
input: "$arrObj",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{
$and: [
{ $eq: ["$$this.arrId", 1] },
{ $lte: ["$$this.total1", "$$this.total2"] }
]
},
{ total2: { $add: ["$$this.total2", 1] } },
"$$this"
]
}
]
}
}
}
}
}]
)
推荐阅读
- python - C++ FIX 实现 --> 会话用户无效。用户名和 SenderCompId 必须匹配
- javascript - 如何制作命令行节点应用程序循环?
- javascript - 只有当来自两个不同元素的两个事件被触发时,如何运行一个函数?
- linux - 尽管我有权限,但关于编辑只读文件的“警告”
- python - 饼图python的值而不是百分比
- vue.js - Vue中如何从$router获取数据
- ios - 关于iOS应用支付架构的一个问题
- python - 根据组的第一个日期将月份累积添加到日期列
- javascript - React Native 如何使轮播重定向到另一个页面并选择相应的 id
- kubernetes - 在没有 k8s 集群的计划期间使用 Terraform 数据资源 kubernetes_all_namespaces