MongoDB has a $mul
field update operator that allows you to multiply a value by a specific amount.
If the field doesn’t already exist, it is created and its value is set to zero (0
) using the same numeric type as the multiplier.
Example
Suppose we have a collection with the following document:
{ "_id" : 1, "bar" : 10 }
We can use the $mul
operator in conjunction with the update()
method to increment the bar
field.
Like this:
db.foo.update(
{ _id: 1 },
{ $mul: { bar: 2 } }
)
Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
This tells us that one document was matched and modified.
Let’s check the collection again:
db.foo.find()
Result:
{ "_id" : 1, "bar" : 20 }
We can see that the amount has doubled to 20.
Multiply a Field that Doesn’t Exist
When you use $mul
on a field that doesn’t exist in the document, the field is added and set to zero (0
) using the same numeric type as the multiplier.
Example:
db.foo.update(
{ _id: 1 },
{ $mul: { bar: 3, extra: 2 } }
)
Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Notice that we updated two fields; the bar
field and the extra
field (which didn’t originally exist).
Let’s check the document again:
db.foo.find()
Result:
{ "_id" : 1, "bar" : 60, "extra" : 0 }
We can see that the bar
field has been multiplied by 3
, and a new extra
field has been added and set to 0
.
Mixed Types
Multiplication with values of mixed numeric types (32-bit integer, 64-bit integer, float) may result in conversion of numeric type.
See the MongoDB documentation for an explanation.