How to decrease the value while keep the minimum as zero in one operation

My existing data:

db.products.insertOne(
   {
     _id: 1,
     sku: "abc123",
     quantity: 10,
     metrics: { orders: 2, ratings: 3.5 }
   }
)

After that, I perform a subtraction on the quantity field.

db.products.updateOne(
   { sku: "abc123" },
   { $inc: { quantity: -20, "metrics.orders": 1 } }
)

My wanted result, minimum vaue of quantity to be zero:

{
  _id: 1,
  sku: 'abc123',
  quantity: 0,
  metrics: { orders: 3, ratings: 3.5 }
}

How can I achieve it using mongoose?

Hello @WONG_TUNG_TUNG,

You can try update with aggregation pipeline,

  • Check if the quantity is less than 0 then update to 0 otherwise do the operation
db.collection.updateOne({
  sku: "abc123"
},
[
  {
    $set: {
      quantity: {
        $cond: {
          if: {
            $lt: [
              { $add: ["$quantity", -20] },
              0
            ]
          },
          then: 0,
          else: { $add: ["$quantity", -20] }
        }
      },
      "metrics.orders": 1
    }
  }
])

Playground

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.