0
0
MongoDBquery~5 mins

Arithmetic expressions ($add, $multiply, $divide) in MongoDB

Choose your learning style9 modes available
Introduction

Arithmetic expressions help you do math with numbers stored in your database. They let you add, multiply, or divide values easily.

Calculate the total price by adding item prices in a shopping cart.
Find the area of a rectangle by multiplying its length and width stored in the database.
Divide a total score by the number of tests to find the average score.
Add tax to a product price by multiplying the price with the tax rate and then adding it.
Adjust quantities by multiplying stored values with a factor, like doubling stock.
Syntax
MongoDB
{ $add: [expression1, expression2, ...] }
{ $multiply: [expression1, expression2, ...] }
{ $divide: [expression1, expression2] }

Use arrays to list the values or fields you want to calculate.

$divide always takes exactly two values: numerator and denominator.

Examples
Adds 10 and 5 to get 15.
MongoDB
{ $add: [10, 5] }
Multiplies the value in the field price by 2.
MongoDB
{ $multiply: ["$price", 2] }
Divides 100 by 4 to get 25.
MongoDB
{ $divide: [100, 4] }
Adds three fields score1, score2, and score3 together.
MongoDB
{ $add: ["$score1", "$score2", "$score3"] }
Sample Program

This query calculates the total score by adding three subject scores, finds the average by dividing the total by 3, and doubles the math score for each student.

MongoDB
db.students.aggregate([
  {
    $project: {
      name: 1,
      totalScore: { $add: ["$math", "$science", "$english"] },
      averageScore: { $divide: [ { $add: ["$math", "$science", "$english"] }, 3 ] },
      doubleMath: { $multiply: ["$math", 2] }
    }
  }
])
OutputSuccess
Important Notes

Make sure fields used in expressions exist and contain numbers to avoid errors.

You can combine these expressions to do more complex calculations.

Remember $divide requires exactly two arguments: numerator and denominator.

Summary

Arithmetic expressions let you do math inside MongoDB queries.

$add sums values, $multiply multiplies, and $divide divides two values.

Use them to calculate totals, averages, or adjust numbers stored in your data.