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!
3
Answers
One possible solution is to use a two-step process:
use updateMany with
$inc
to increment the count fields of the documents.use another
updateMany
operation with$max
to set any negative count fields to zero.Note: this is not an atomic operation, you might need to use a transaction
Please see if the below query is useful, it uses $cond and $expr.
It is possible to complete all operations in one shot with aggregation in an update pipeline.
$inc
: chain up$add
result with$max
with 0 to bound it to zero if it is negative$addToSet
: put them in a$setUnion
to perform the same behaviour$set
: just put the other entries in the$set
stageMongo Playground