首页 > 解决方案 > 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 个字段,并基于它增加一个字段值。提前致谢。

标签: mongodbmongoosemongodb-query

解决方案


从 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"
                ]
              }
            ]
          }
        }
      }
    }
  }]
)

操场


推荐阅读