Home > Software design >  $inc with min value MongoDB
$inc with min value MongoDB

Time:10-12

I need to update a specific document (by _id) and lower in DB a specific field by 1.

The query looks like this :

mycollection.update_one({"_id": {"$eq": the_id}}, {"$inc": {"fieldToLower": -1}})

However i need the fieldToLower to never be negative, that mins equals to 0 in case it's already 0, and not equal to -1.

I would like to know how can i do that in this query ?

CodePudding user response:

As a workaround you can update only values where fieldToLower is > 0 like this:

mycollection.update_one({
  "_id": the_id,
  "fieldToLower": {
    "$gte": 1
  }
},
{
  "$inc": {
    "fieldToLower": -1
  }
})

Example here

  • Related