Introduction
The $mul operator multiplies the value of a field by a specified number. It helps update numbers easily without manual calculation.
The $mul operator multiplies the value of a field by a specified number. It helps update numbers easily without manual calculation.
{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }Use inside an update command to multiply fields.
Only numeric fields can be multiplied.
price field by 1.1 (increase by 10%) for the product with _id 1.db.products.updateOne({ _id: 1 }, { $mul: { price: 1.1 } })quantity field for all orders.db.orders.updateMany({}, { $mul: { quantity: 2 } })stock field for the item named 'pen'.db.items.updateOne({ name: 'pen' }, { $mul: { stock: 0.5 } })This example first adds two products. Then it increases the price of the product with _id 1 by 20% using $mul. Finally, it shows the updated product.
db.products.insertMany([
{ _id: 1, name: 'Notebook', price: 10 },
{ _id: 2, name: 'Pen', price: 5 }
])
// Multiply price by 1.2 (increase by 20%) for product with _id 1
const result = db.products.updateOne({ _id: 1 }, { $mul: { price: 1.2 } })
// Find updated document
const updatedProduct = db.products.findOne({ _id: 1 })
updatedProductIf the field does not exist, $mul creates it with value 0.
Multiplying by 1 keeps the value unchanged.
$mul multiplies numeric fields by a given number.
Use it in update commands to change values without manual math.
It works on one or many fields at once.
$mul operator do in MongoDB?$mul$mul operator is used to multiply the value of a numeric field by a given number in an update operation.$inc which adds, or $div which divides, $mul specifically multiplies the field value.$mul = multiply [OK]price by 3 in a MongoDB update?$mul operator requires a field name as key and a numeric multiplier as value.{ $mul: { price: 3 } }. { $mul: { 3: price } } reverses key and value. { $mul: { price: "3" } } uses a string instead of number. { $mul: { price: price * 3 } } uses an invalid expression.{ _id: 1, quantity: 5, price: 10 }, what will be the document after running db.collection.updateOne({ _id: 1 }, { $mul: { quantity: 2, price: 3 } })?$mul operator multiplies each specified field by the given number. Here, quantity is multiplied by 2 and price by 3.quantity 5 * 2 = 10, original price 10 * 3 = 30.db.products.updateOne({ _id: 2 }, { $mul: { stock: '2' } }). What is the issue?$mul operator requires the multiplier to be a number, not a string.score field only if it is greater than 10 in documents. Which update query correctly uses $mul with a filter?score is greater than 10.$mul to multiply score by 2 for those documents.Pass the test and this pattern moves unknown