Home > other >  updateOne based on condition
updateOne based on condition

Time:05-25

await products.updateOne(
        {
          $and: [
            { name: { $eq: name } },
            { $expr: { $lt: ["$remaining", "$capacity"] } },
          ],
        },
        { $inc: { remaining: 1 } },
        { returnOriginal: false }
      );

Instead of having the condition in the query like so { $expr: { $lt: ["$remaining", "$capacity"] } }, is there a way to include this condition in the update argument?

The reason for this is so that I want the returned matchCount to return 1 if the name is matched.

CodePudding user response:

Yes, you can do that if you use mongo 4.2 using aggregate update.

db.collection.update({
  $and: [ //condition goes here
    {
      name: {
        $eq: "name"
      }
    },
    
  ],
  
},
[
  {
    "$set": { //conditional update
      "remaining": {
        "$switch": {
          "branches": [
            {
              case: {
                $lt: [ //condition to update
                  "$remaining",
                  "$capacity"
                ]
              },
              then: {
                $add: [ //true case
                  "$remaining",
                  1
                ]
              }
            }
          ],
          default: {
            $add: [ //if no match
              "$remaining",
              0
            ]
          }
        }
      }
    }
  }
])

playground

  • Related