sv_savage
(Sv Savage)
February 12, 2023, 7:28pm
#1
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 @sv_savage ,
Welcome to the MongoDB Community forums
sv_savage:
db.serial.findAndModify({ query: {}, update: { $inc: {serial: { $floor: { $multiply: [ { $rand: {} }, 100 ]}}}}, new: true})
and I get Cannot increment with the non-numeric argument
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