【问题标题】:MongoDB - $lte 2 keys against each other in the same objectMongoDB - $lte 2个键在同一个对象中相互对抗
【发布时间】:2020-12-22 08:13:36
【问题描述】:

样本数据:

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 mongoose mongodb-query


    【解决方案1】:

    您可以从 MongoDB v4.2 开始使用update with aggregation pipeline

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

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2023-01-09
      • 2022-01-08
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多