Introduction to MongoDB $divide Operator

In MongoDB, the $divide operator is used to divide a numeric field by another numeric field or constant.

Syntax

The syntax of the $divide operator is as follows:

{ $divide: [ <number1>, <number2> ] }

Here, <number1> and <number2> can be field names, numbers, or expressions.

Use Cases

The $divide operator can be used to perform division operations, such as calculating the ratio of salary to work hours for each employee or calculating the average price for each order. The $divide operator can be used with other operators, such as the $group or $project operator.

Examples

Suppose there is a collection of employee data that includes the name, hours worked, and salary of each employee. To calculate the average hourly salary for each employee, the $divide operator can be used.

Here is an example dataset:

db.employees.insertMany([
  { name: "Alice", hours_worked: 40, salary: 4000 },
  { name: "Bob", hours_worked: 35, salary: 3500 },
  { name: "Charlie", hours_worked: 45, salary: 4500 }
])

The following statement calculates the average hourly salary for each employee:

db.employees.aggregate([
  {
    $project: {
      name: 1,
      hourly_salary: { $divide: ["$salary", "$hours_worked"] }
    }
  }
])

In the example above, the $project operator transforms each document in the result set into a new document containing the employee name and the calculated hourly salary. The $divide operator is used to calculate the hourly salary for each employee.

Conclusion

Using the $divide operator, various useful metrics can be calculated by performing division operations in MongoDB.