$divide (arithmetic expression)

APPLIES TO: MongoDB vCore

The $divide operator divides two numbers and returns the quotient. The operator returns an error if the divisor is zero.

Syntax

The syntax for the $divide operator is as follows:

{ $divide: [ <dividend>, <divisor> ] }

Parameters

Description
<dividend> Any valid expression that resolves to a number to be divided.
<divisor> Any valid expression that resolves to a nonzero number to divide by.

Example

Let's understand the usage with sample data from the stores dataset to calculate the average sales per staff member and percentage of full-time staff.

db.stores.aggregate([
  { $match: { "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74" } },
  {
    $project: {
      name: 1,
      averageSalesPerStaff: {
        $divide: [
          "$sales.totalSales",
          { $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] }
        ]
      },
      fullTimeStaffPercentage: {
        $multiply: [{
          $divide: [
            "$staff.totalStaff.fullTime",
            { $add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"] }
          ]
        }, 100]
      }
    }
  }
])

This produces the following output:

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
  "averageSalesPerStaff": 3893.95,
  "fullTimeStaffPercentage": 48.72
}