- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $mul
$mul¶
On this page
Definition¶
-
$mul
¶ Multiply the value of a field by a number. To specify a
$mul
expression, use the following prototype:The field to update must contain a numeric value.
To specify a
<field>
in an embedded document or in an array, use dot notation.
Behavior¶
Starting in MongoDB 5.0, mongod
no longer raises an
error when you use an update operator like $mul
with an empty operand expression ( { }
). An empty update results
in no changes and no oplog entry is created (meaning that the
operation is a no-op).
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.
Missing Field¶
If the field does not exist in a document, $mul
creates the
field and sets the value to zero of the same numeric type as the
multiplier.
Mixed Type¶
Multiplication with values of mixed numeric types (32-bit integer, 64-bit integer, float) may result in conversion of numeric type. For multiplication with values of mixed numeric types, the following type conversion rules apply:
32-bit Integer | 64-bit Integer | Float | |
---|---|---|---|
32-bit Integer | 32-bit or 64-bit Integer | 64-bit Integer | Float |
64-bit Integer | 64-bit Integer | 64-bit Integer | Float |
Float | Float | Float | Float |
Note
- If the product of two 32-bit integers exceeds the maximum value for a 32-bit integer, the result is a 64-bit integer.
- Integer operations of any type that exceed the maximum value for a 64-bit integer produce an error.
Examples¶
Multiply the Value of a Field¶
Create the products
collection:
In the following operation, db.collection.updateOne()
updates
the document. The $mul
operator multiplies the price
field by 1.25
and the quantity
field by 2
:
In the updated document:
price
is the original value, 10.99, multiplied by 1.25quantity
is the original value, 25, multiplied by 2
Apply $mul
Operator to a Non-existing Field¶
Add the following document to the products
collection:
In the following operation, db.collection.updateOne()
attempts to
apply the $mul
operator to a field that is not in the document:
The db.collection.updateOne()
operation
- inserts the
price
field - sets Decimal128(“0”)
The price
field has the same type, Decimal128, as the multiplier.
Multiply Mixed Numeric Types¶
Add the following document to the products
collection:
In the following operation, db.collection.updateOne()
uses
the $mul
operator to multiply the value in the price
field Decimal128(10) by Int32(5):
The operation results in the following document:
The value in the price
field is of type Decimal128. See Multiplication Type Conversion Rules for details.