0
0
MongoDBquery~5 mins

$mul operator for multiplication in MongoDB

Choose your learning style9 modes available
Introduction

The $mul operator multiplies the value of a field by a specified number. It helps update numbers easily without manual calculation.

You want to increase prices by a fixed percentage in a product list.
You need to double the quantity of items in an order.
You want to apply a discount factor by multiplying the original price.
You want to adjust scores or ratings by multiplying them with a factor.
Syntax
MongoDB
{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }

Use inside an update command to multiply fields.

Only numeric fields can be multiplied.

Examples
Multiply the price field by 1.1 (increase by 10%) for the product with _id 1.
MongoDB
db.products.updateOne({ _id: 1 }, { $mul: { price: 1.1 } })
Double the quantity field for all orders.
MongoDB
db.orders.updateMany({}, { $mul: { quantity: 2 } })
Halve the stock field for the item named 'pen'.
MongoDB
db.items.updateOne({ name: 'pen' }, { $mul: { stock: 0.5 } })
Sample Program

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.

MongoDB
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 })

updatedProduct
OutputSuccess
Important Notes

If the field does not exist, $mul creates it with value 0.

Multiplying by 1 keeps the value unchanged.

Summary

$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.