MongoDB - $mul Operator
MongoDB $mul
operator is a powerful update operator used to multiply the value of a field by a specified number. This operator allows for direct arithmetic operations within the database, making it particularly useful for scenarios that require modifying numeric field values without needing to retrieve the current value first.
In this article, We will learn about the MongoDB $mul Operator in detail, covering its syntax, use cases, and practical examples, so we can use this powerful feature in our MongoDB projects efficiently.
What is the MongoDB $mul Operator?
MongoDB $mul Operator is an update operator used to multiply the value of a field by a specified number. It is used in update operations to modify the existing value of a field without having to read the current value first. This operator is particularly useful when we need to perform arithmetic operations directly within the database. $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.
Key Features of the MongoDB $mul
Operator
- Efficient Numeric Updates: Perform direct arithmetic multiplication on numeric fields without having to retrieve and modify data in your application code.
- Atomicity: The
$mul
operator ensures that updates are atomic within a single document, maintaining data consistency. - Automatic Field Creation: If the target field does not exist, MongoDB will add the field and set its value to zero before applying the multiplication
. - Numeric Type Handling: The operator works only with numeric types (integers, floats, etc.). It automatically adjusts the numeric type if there’s a mismatch between operand types.
How the $mul
Operator Works with Mixed Numeric Types
MongoDB allows arithmetic operations between fields of different numeric types, such as 32-bit integers, 64-bit integers, and floats. Here’s how the operation handles mixed numeric types. The following below 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: { <field>: <number> } }
Key Terms
<
field
>
: The field we want to update.<
number
>
: The number by which to multiply the field value.
Examples of MongoDB $mul Operator
To help us understand the practical applications of the $mul
operator, let's explore some examples using the Fruits database with a Details collection. The collection contains fruit-related data, including the name
, price
, and quantity
fields.
- Database: Fruits
- Collection: Details
- Document: two documents that contain the details of the fruits in the form of field-value pairs.
Example 1: Multiply 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:
Explanation:
- The query targets the mango document in the
Details
collection. - The
price
field is multiplied by2.10
. TheNumberDecimal
type ensures that we maintain precision with decimal numbers.
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:
Explanation:
- The
quantity.tQuantity
field is accessed using dot notation and multiplied by3
. - This showcases how we can use the
$mul
operator to modify fields within embedded documents.
Example 3: Apply $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:
Explanation: Since the batchNumber
field doesn’t exist in the document, MongoDB will create it and set its value to 0
before multiplying it by 230
.
Example 4: Multiply Mixed Numeric Types
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:
Explanation: The price
field is a float. The $mul
operator will multiply it by 5
, and the result will also be a float due to type conversion.
Important Points About $mul Operator
Before diving into more advanced usage, here are some essential points about the $mul
operator to keep in mind:
- Only Numeric Fields: The
$mul
operator works only with fields containing numeric values (integers or floats). Using it on non-numeric fields will result in an error. - Field Creation: If the target field doesn’t exist in the document, MongoDB will add it and assign a value of
0
before applying the multiplication. - Atomic Operation: The
$mul
operator is atomic at the document level. This ensures that updates to numeric fields are applied in a consistent and isolated manner. - Handling Mixed Types: MongoDB automatically converts the result to the appropriate numeric type (e.g., integer to float) when operands are of different numeric types.
Conclusion
The MongoDB $mul
operator is an essential tool for performing arithmetic operations directly within the database which allowing for efficient updates to numeric fields. By understanding its syntax and use cases, we can use this operator to simplify and optimize our database operations. Whether updating prices, quantities, or other numeric fields, the $mul
operator provides a powerful and flexible solution for our MongoDB applications.