$subtract

The `$subtract` operator is used to subtract two numbers and return the result.

Syntax

{ $subtract: [ <expression 1>, <expression 2> ] }

Parameters

<expression 1>stringrequired

The minuend (the number from which another number is to be subtracted).

<expression 2>stringrequired

The subtrahend (the number to be subtracted).

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "staff": {
    "employeeCount": { "fullTime": 20, "partTime": 18 }
  }
}

Calculating the difference between full time and part time staff

Calculate the absolute difference in part time and full time staff using $subtract and $abs operators.

Query:

db.stores.aggregate([
  { $match: { company: { $in: ["First Up Consultants"] } } },
  {
    $project: {
      name: 1,
      staff: 1,
      staffCountDiff: {
        $abs: {
          $subtract: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"]
        }
      }
    }
  }
])

Output:

[
  {
    "_id": "62438f5f-0c56-4a21-8c6c-6bfa479494ad",
    "name": "First Up Consultants | Plumbing Supply Shoppe",
    "staff": { "employeeCount": { "fullTime": 20, "partTime": 18 } },
    "staffCountDiff": 2
  }
]