How to restrict a field's value while updating using $inc?

Quick question, is there a way for a field to have a maximum value? For example the field “cards” can only have a maximum value of 100. So if you would increment above it it would return to its maximum value.

You can use an Updates with Aggregation Pipeline to check while updating and set the value 100 if it exceeds 100. Note that this feature is available with MongoDB v4.2 or later.

Alright could you give me a more concrete small example of how to achieve that? Because from reading that page their doesn’t seem to be clear example of how to do that.

Assuming the field you want to increment is fld and the value you want to increment is INC_VALUE, then this pipeline can be used to do the required update:

  $set: { 
      fld: { 
          $cond: { 
              if: { $gt: [ { $add: [ "$fld", INC_VALUE ] }, 100 ] }, 
              then: 100, 
              else: { $add: [ "$fld", INC_VALUE ] } 
1 Like

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