How to Use $mul Operator in MongoDB for Multiplying Field Values
In MongoDB, the
$mul operator multiplies the value of a field by a specified number during an update. You use it inside an updateOne or updateMany command with the $mul key and the multiplication factor as the value.Syntax
The $mul operator is used in an update statement to multiply the value of a field by a given number. It takes an object where the key is the field name and the value is the multiplier.
- Field: The name of the field to multiply.
- Multiplier: The number to multiply the field's current value by.
json
{
$mul: { <field>: <number> }
}Example
This example shows how to multiply the price field by 1.1 (increasing it by 10%) for a product with _id 1.
javascript
db.products.updateOne(
{ _id: 1 },
{ $mul: { price: 1.1 } }
);Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes when using $mul include:
- Trying to multiply a field that does not exist or is not a number, which will cause no change or an error.
- Using
$muloutside of an update operation. - Confusing
$mulwith arithmetic operators in queries (it only works in updates).
javascript
/* Wrong: Using $mul in a find query (invalid) */ db.products.find({ $mul: { price: 2 } }); /* Right: Use $mul inside update */ db.products.updateOne({ _id: 1 }, { $mul: { price: 2 } });
Quick Reference
| Operator | Purpose | Usage Example |
|---|---|---|
| $mul | Multiply a field by a number | { $mul: { quantity: 3 } } |
| $inc | Increment a field by a number | { $inc: { quantity: 3 } } |
| $set | Set a field to a value | { $set: { quantity: 10 } } |
Key Takeaways
Use $mul inside update commands to multiply a field's value by a number.
The field must exist and be numeric for $mul to work correctly.
$mul cannot be used in query filters, only in updates.
Always check the update result to confirm the operation succeeded.