MongoDB – $mul Operator
MongoDB $mul or multiple operator is a type of field update operator. $mul operator multiplies the value of the field by a number.
Important Points
- $mul operator only updates those fields whose values are of numeric type like int, float, etc.
- If the specified field is not present in the document, then this operator will add that field in the document and assign the value of that field to zero of the same numeric type as the multiplier.
- This operator is an atomic operation within a single document.
- In this operator, multiplication with values of mixed numeric types like 32-bit integer, 64-bit integer, float, etc., may result in the conversion of numeric type.
- The following rules are applied in the multiplication with the values of mixed numeric types:
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 |
Syntax:
{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }
MongoDB $mul Operator Example
Database: Fruits
Collection: Details
Document: two documents that contain the details of the fruits in the form of field-value pairs.
Example 1: Multiplying the value of a field
In this example, we are multiplying the value of the price field by 2.10 in the document which matches the specified condition, i.e., name = mango.
Query:
db.Details.update({name: "mango"}, {$mul: {price: NumberDecimal("2.10")}})
Output:
Example 2: Multiplying the value of a field in the embedded/nested document
In this example, we are multiplying the value of quantity.tQuantity field by 3 in the document that matches the specified condition, i.e., name = mango.
Query:
db.Details.update({name: "mango"}, {$mul: {"quantity.tQuantity": 3}})
Output:
Example 3: Using $mul operator to a non-existing field
In this example, we are applying $mul operator to a non-existing field in the document that matches the specified condition, i.e., name = apple.
Query:
db.Details.update({name: "apple"}, {$mul: {"batchNumber":NumberInt(230)}})
Output:
Example 4: Using $mul operator to multiply mixed numeric type
In this example, we are multiplying the value(float type) of the price field in the document that matches the specified condition, i.e., name = apple.
Query:
db.Details.update({name: "apple"}, {$mul: {price: NumberDecimal(5)}})
Output:
Key Takeaways About $mul Operator
- The $mul operator in MongoDB is used to multiply the value of a field by a specified number.
- The field to update must contain a numeric value for the $mul operator to work.
- You can use this operator in methods like update(), findAndModify(), etc.
- Multiplication with values of mixed numeric types (32-bit integer, 64-bit integer, float) may result in conversion of numeric type.
- The $mul operator can be used in embedded documents or arrays using dot notation.
Contact Us