$divide
The $divide operator in the Amazon DocumentDB aggregation pipeline is used to divide one number by another. It is a useful operator for performing mathematical operations on numeric fields within your documents.
Parameters
-
numerator: The dividend or the number to be divided. -
denominator: The divisor or the number to divide by.
Example (MongoDB Shell)
This example demonstrates how to use the $divide operator to calculate the hourly rate for employees based on their yearly salary and the number of working hours per year.
Create sample documents
db.employees.insertMany([ { _id: 1, name: "John Doe", salary: 80000, hoursPerYear: 2080 }, { _id: 2, name: "Jane Smith", salary: 90000, hoursPerYear: 2080 }, { _id: 3, name: "Bob Johnson", salary: 75000, hoursPerYear: 2080 } ]);
Query example
db.employees.aggregate([ { $project: { name: 1, hourlyRate: { $divide: ["$salary", "$hoursPerYear"] } } } ])
Output
[
{ "_id" : 1, "name" : "John Doe", "hourlyRate" : 38.46153846153846 },
{ "_id" : 2, "name" : "Jane Smith", "hourlyRate" : 43.26923076923077 },
{ "_id" : 3, "name" : "Bob Johnson", "hourlyRate" : 36.05769230769231 }
]
Code examples
To view a code example for using the $divide command, choose the tab for the language that you want to use: