I’m using MongoDB and I have a document where I want to increment a count field. However, I need to ensure that this count does not go below zero. For example, if inc is -2 and the current count is 1, applying $inc will result in -1, which I want to avoid.
Here’s the current update operation I’m using:
db.collection.updateMany(
{ '_id': {'$in': object_ids} },
{
'$inc': { 'count': inc },
'$addToSet': {...},
'$set': {...},
}
)
I’ve tried these 2 , but as ‘$addToSet’ can not be added as a pipeline stage I can not use sth like this:
db.collection.updateMany({ '_id': {'$in': object_ids} }, [ { $set: { count: { $cond: { if: { $gte: [{ $add: ['$count', inc] }, 0] }, then: { $add: ['$count', inc] }, else: 0 } } } } ] )
I also thought of using '$expr': { '$gte': ['$count', 0] }
, but this doesn’t prevent decrementing to negative!
I3_T_00 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.