$inc value using $floor return "Cannot increment with non-numeric argument"

I am trying to increment a value by some random amount.

db.serial.findAndModify({ query: {}, update: { $inc: {serial: { $floor: { $multiply: [ { $rand: {} }, 100 ]}}}}, new: true})

and I get Cannot increment with the non-numeric argument

I have even tried

db.serial.findAndModify({ query: {}, update: { $inc: {serial: { $floor:  3.12 }}}, new: true})

and get the same error.

I expect the value to be incremented by 3 in the second example, and some random number between 0-100 in the first.

Why? and how to fix it?

Hi :wave: @sv_savage,

Welcome to the MongoDB Community forums :sparkles:

The error is because $inc requires the parameter to be a numeric value and not a document.

To fix this, the update operation should use valid atomic operators that work for incrementing the field with a numeric value. One possible solution could be:

db.users.findAndModify( {query: {}, update: { $inc: { serial: Math.floor(Math.random() * 100) } }})

Note: It is basically javascript, so the value of Math.floor(Math.random() * 100) will be calculated on the client side.

Here, it will increment the "serial" field with the rounded value of a random number between 0 and 100.

I hope it helps!

Thanks,
Kushagra