Introduction to MongoDB $mul Operator
$mul
is an update operator in MongoDB used to multiply the value of a field by a given number. This operator is used to update a field in a document by multiplying its value with a given number. $mul
can be used to increase the value of numeric fields.
Syntax
The syntax for the $mul
operator is as follows:
{ $mul: { <field1>: <number1>, ... } }
Here, <field>
is the name of the field to be multiplied by the given number, and <number>
is the number to multiply with.
Use Cases
The $mul
operator is commonly used to update fields of numeric type. For example, it can be used to decrease the price of a product by 20%, or increase the stock quantity by 50%.
Examples
Example 1
Consider the following product document:
{
_id: 1,
name: "iPhone 13",
price: 999,
stock: 100
}
Now, let’s say we want to decrease the price of iPhone 13 by 20%. We can use the $mul
operator to update the document as follows:
db.products.updateOne({ _id: 1 }, { $mul: { price: 0.8 } })
In the above code, we use the $mul
operator to multiply the value of the price
field by 0.8 (i.e., decrease it by 20%). The updated document will look like this:
{
_id: 1,
name: "iPhone 13",
price: 799.2,
stock: 100
}
Example 2
Consider the following order document:
{
_id: 1,
customer: "Alice",
items: [
{ product: "iPhone 13", quantity: 2, price: 999 },
{ product: "AirPods", quantity: 1, price: 159 },
],
total: 2157
}
Now, let’s say we want to decrease the price of all items in the order by 10%. We can use the $mul
operator to update the document as follows:
db.orders.updateOne({ _id: 1 }, { $mul: { "items.$[].price": 0.9 } })
In the above code, we use the $mul
operator to multiply the value of the items.$[].price
field by 0.9 (i.e., decrease it by 10%). Here, the $[]
positional operator is used to update all elements in the array. The updated document will look like this:
{
_id: 1,
customer: "Alice",
items: [
{ product: "iPhone 13", quantity: 2, price: 899.1 },
{ product: "AirPods", quantity: 1, price: 143.1 },
],
total: 1941.3
}
Conclusion
The $mul
operator can be used in MongoDB’s update operations to multiply the value of a field by a specified multiplier and store the result back in the original document. In some cases, the $mul
operator can improve the performance of update operations, as it only modifies the specified fields in the document. However, it should be noted that the $mul
operator only applies to fields of numeric type.
In summary, the $mul
operator can be used for update operations in MongoDB to multiply the value of a specified field by a given number and save the result back to the original document. This operator is applicable to fields of numeric types and can improve the performance of update operations.