Introduction to MongoDB $multiply Operator
$multiply
is an aggregation operator in MongoDB used to calculate the product of two numbers in an expression and return the result. It can be used in the aggregation pipeline.
Syntax
The syntax of the $multiply
operator is as follows:
{ $multiply: [ <expression1>, <expression2>, ... ] }
Here, <expression1>
and <expression2>
are the two expressions to be multiplied. Any number of expressions can be used for multiplication.
Use Cases
The $multiply
operator is typically used for numeric calculations in the aggregation pipeline, such as calculating the total price of orders, calculating employee salaries, etc. It can also be used in conjunction with other aggregation operators such as $group
and $project
.
Examples
Sample Data
Assuming we have a orders
collection storing sales orders with the following documents:
{ "_id": 1, "item": "apple", "price": 0.50, "quantity": 10 }
{ "_id": 2, "item": "orange", "price": 0.75, "quantity": 5 }
{ "_id": 3, "item": "banana", "price": 0.25, "quantity": 20 }
Example 1: Calculate the Total Price of Orders
The following aggregation pipeline uses the $multiply
operator to calculate the total price of orders:
db.orders.aggregate([
{
$project: {
total: { $multiply: ["$price", "$quantity"] }
}
}
])
The pipeline uses the $project
operator to multiply the price
and quantity
fields of each document and store the result in a new total
field. Here’s the output of the pipeline:
{ "_id": 1, "total": 5 }
{ "_id": 2, "total": 3.75 }
{ "_id": 3, "total": 5 }
Example 2: Calculate Employee Monthly Salary
Assuming we have an employees
collection storing employee information with the following documents:
{ "_id": 1, "name": "Alice", "hourly_rate": 10, "hours_worked": 160 }
{ "_id": 2, "name": "Bob", "hourly_rate": 15, "hours_worked": 140 }
{ "_id": 3, "name": "Charlie", "hourly_rate": 12, "hours_worked": 180 }
The following aggregation pipeline uses the $multiply
operator to calculate the monthly salary of each employee:
db.employees.aggregate([
{
$project: {
monthly_salary: { $multiply: ["$hourly_rate", "$hours_worked", 30] }
}
}
])
The pipeline uses the $project
operator to multiply the hourly_rate
and hours_worked
fields of each document and multiply the result by 30 (assuming there are 30 days in a month).
Conclusion
In MongoDB, $multiply
is an aggregation operator used to calculate the product of two numbers in an expression and return the result. It can be used in the aggregation pipeline.