MongoDB

MongoDB $DateDiff Operator

To deal with dates, MongoDB has several different date operators. The $dateDiff operator, which also accepts the date expression to deal with the date, is one of these operators. The $dateDiff expression prints the numeric difference between the startDate and endDate expressed in the defined units. The $dateDiff operator expression must contain the startDate, endDate, and the unit parameter. The “timezone” and the “startOfWeek” parameter are optional in the $dateDiff operator. The algorithm of the $dateDiff operator uses the Gregorian calendar to determine the date difference. Furthermore, the $dateDiff operator only takes leap years and daylight time, while the leap seconds are not taken into consideration.

How to Use the $DateDiff Operator in MongoDB

The $dateDiff operator returns the difference between two dates in the given unit. The $dateDiff operator has various parameters in which the startDate, endDate, and unit parameters are required. Without these parameters, we may encounter the MongoDB server error. We use the “Project” collection to work with the $dateDiff operator. The “Project” collection is initially empty which can be inserted with the documents by applying the following query:

db.Project.insertMany([
      {
          "PId": 1,
          "Project" : "Android Application",
          "Month": "January",
          "Team": 10,
      "StartDate" : ISODate("2020-01-05"),
      "EndDate" : ISODate("2021-01-10")
         
      },
       {
         "PId": 2,
          "Project" : "Drone",
          "Month": "February",
          "Team": 20,
      "StartDate" : ISODate("2023-02-01"),
      "EndDate" : ISODate("2024-02-28")
         
      },
   {
         "PId": 3,
          "Project" : "Shopping Website",
          "Month": "March",
          "Team": 5,
      "StartDate" : ISODate("2021-03-25"),
      "EndDate" : ISODate("2022-03-01")
         
      },
       {
          "PId": 4,
          "Project" : "Software Management",
          "Month": "May",
          "Team": 9,
      "StartDate" : ISODate("2022-05-01"),
      "EndDate" : ISODate("2023-05-31")
         
}
  ])

The previous query inserted the documents in the “Project” collection of MongoDB as the result is shown. Now, we can see that all the documents have two fields that contain the ISO format date. We use these date fields over the $dateDiff operator to find out the difference in these dates.

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63c53402b91c87f8b6a855f8"),
    '1': ObjectId("63c53402b91c87f8b6a855f9"),
    '2': ObjectId("63c53402b91c87f8b6a855fa"),
    '3': ObjectId("63c53402b91c87f8b6a855fb")
  }
}

Example 1: Using the $DateDiff in MongoDB for the Difference Between Date

The $dateDiff operator is employed on the “StartDate” and “EndDate” fields of all documents of the collection to get the difference in these dates which is an integer value. We use the aggregate method where the $project stage is employed to include the fields. We include the StartDate and EndDate fields as the value of “1” is specified to them. After that, we insert a “result” field where the $dateDiff operator is defined with its parameter. We set the “startDate” parameter which marks the beginning of the time.

Here, we provide the $StartDate field to the “startDate” parameter. Then, we set the “endDate” parameter where the date period time ends, and we give the “$EndDate” field. After that, we provide another required “unit” parameter to the $dateDiff operator to which we assign a “day” value. This parameter measures the time between the startDate and the endDate. The pretty() method of MongoDB generates the results of the $dateDiff operator in a structured manner.

db.Project.aggregate(
   [
      {
         $project:
            {
               Start: "$StartDate",
               End: "$EndDate",
               result:
                  {
                     $dateDiff:
                        {
                           startDate: "$StartDate",
                           endDate: "$EndDate",
                           unit: "day"
                        }
                  }
  }
}
])

The difference between the startDate and endDate of each provided document date is displayed in a numeric value against the “result” field according to the specified unit in the $dateDiff operator.

[
  {
    _id: ObjectId("63c53466b91c87f8b6a855fc"),
    Start: ISODate("2020-01-05T00:00:00.000Z"),
    End: ISODate("2021-01-10T00:00:00.000Z"),
    result: Long("371")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855fd"),
    Start: ISODate("2023-02-01T00:00:00.000Z"),
    End: ISODate("2024-02-28T00:00:00.000Z"),
    result: Long("392")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855fe"),
    Start: ISODate("2021-03-25T00:00:00.000Z"),
    End: ISODate("2022-03-01T00:00:00.000Z"),
    result: Long("341")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855ff"),
    Start: ISODate("2022-05-01T00:00:00.000Z"),
    End: ISODate("2023-05-31T00:00:00.000Z"),
    result: Long("395")
  }
]

Example 2: Using the $DateDiff in MongoDB to Find the Difference Between the Date and a Number

If we try to get the difference of the startDate from the number field, the error is raised in MongoDB because of the invalid argument value. Here, we set the $dateDiff operator within the “result” attribute of the $project operator. The $dateDiff operator takes the “startDate” argument where the “$StartDate” field of the document is given. Then, we input the “endDate” where the “Team” field is provided. The $Team field is stored with the numeric value which cannot be used for the difference operator by the $dateDiff operator. Then, we assign a “day” value to the “unit” argument.

db.Project.aggregate(
   [
     { $project: {
       result: {
         $dateDiff:
                        {
                           startDate: "$StartDate",
                           endDate: "$Team",
                           unit: "day"
                        }
         }
    }
  }
]).pretty()

We have a following MongoDB server error because the “endDate” parameter is not a date value. Thus, it is required for the $dateDiff operator to only deal with dates.

MongoServerError: PlanExecutor error during aggregation :: caused by :: $dateDiff requires 'endDate' to be a date, but got int.

Example 3: Using the $DateDiff in MongoDB to Subtract the EndDate from the StartDate

The next case of the $dateDiff operator is where we switch the values of the “startDate” and “endDate” parameters. Then, the generated results are in the negative values. Let’s have the following $dateDiff operator query where we deploy the $dateDiff operator. The $dateDiff operator is inputted with the “startDate” parameter where the “EndDate” field is assigned. On the other hand, we give a “StartDate” field which is the starting time to the “endDate” parameter. The $dateDiff operator returns the difference between the “EndDate” values from the “StartDate” values. After that, we set the unit parameter with the “day” to measure the given periods of the dates.

db.Project.aggregate(
   [
     { $project: {
       result: {
         $dateDiff:
                        {
                           startDate: "$EndDate",
                           endDate : "$StartDate",
                           unit: "day"
                        }
         }
      }
   }
   ]
).pretty()

The $dateDiff operator outputs the dates of the document in the “result” field where all the values are in a negative form due to the switch argument values.

[
  { _id: ObjectId("63c53466b91c87f8b6a855fc"), result: Long("-371") },
  { _id: ObjectId("63c53466b91c87f8b6a855fd"), result: Long("-392") },
  { _id: ObjectId("63c53466b91c87f8b6a855fe"), result: Long("-341") },
  { _id: ObjectId("63c53466b91c87f8b6a855ff"), result: Long("-395") }
]

Example 4: Using the $DateDiff in MongoDB with the Different Unit Values

The time difference that is measured in integer units is returned by the $dateDiff expression. A unit has no fractional parts. There are no half-years when counting in years. We execute the query of this statement where the $dateDiff operator “unit” argument is used with different values. We create the “YearUnit” field within the $project operator and employ the $dateDiff operator there. The $dateDiff operator takes the values against the “startDate” and “endDate” arguments.

Note that we set the “year” period in the “unit” argument. The difference between the specified dates is evaluated based on the year unit. After that, we have another field which is “MonthUnit” where the $dateDiff operator is specified with the “unit” value “month”. Next, the “DayUnit” field of the $project operator is called the $dateDiff with the “unit” value as “day” to measure the period difference of the dates with the daytime unit.

db.Project.aggregate(
   [
      {
         $project:
            {
               StartDate: "$StartDate",
               EndDate: "$EndDate",
               YearUnit:
                  {
                     $dateDiff:
                        {
                           startDate: "$StartDate",
                           endDate: "$EndDate",
                           unit: "year"
                        }
                  },
               MonthUnit:
                  {
                     $dateDiff:
                        {
                           startDate: "$StartDate",
                           endDate: "$EndDate",
                           unit: "month"
                        }
                  },
               DaysUnit:
                  {
                     $dateDiff:
                        {
                           startDate: "$StartDate",
                           endDate: "$EndDate",
                           unit: "day"
                        }
                  }
            }
       }
   ]
 )

The date differences are returned in the given unit values by the $dateDiff operator.

[
  {
    _id: ObjectId("63c53466b91c87f8b6a855fc"),
    StartDate: ISODate("2020-01-05T00:00:00.000Z"),
    EndDate: ISODate("2021-01-10T00:00:00.000Z"),
    YearUnit: Long("1"),
    MonthUnit: Long("12"),
    DaysUnit: Long("371")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855fd"),
    StartDate: ISODate("2023-02-01T00:00:00.000Z"),
    EndDate: ISODate("2024-02-28T00:00:00.000Z"),
    YearUnit: Long("1"),
    MonthUnit: Long("12"),
    DaysUnit: Long("392")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855fe"),
    StartDate: ISODate("2021-03-25T00:00:00.000Z"),
    EndDate: ISODate("2022-03-01T00:00:00.000Z"),
    YearUnit: Long("1"),
    MonthUnit: Long("12"),
    DaysUnit: Long("341")
  },
  {
    _id: ObjectId("63c53466b91c87f8b6a855ff"),
    StartDate: ISODate("2022-05-01T00:00:00.000Z"),
    EndDate: ISODate("2023-05-31T00:00:00.000Z"),
    YearUnit: Long("1"),
    MonthUnit: Long("12"),
    DaysUnit: Long("395")
  }
]

Conclusion

The article explored the new MongoDB $dateDiff operator where the difference operation is conducted between the two dates. We used the $dateDiff operator to get the difference between the values from the specified dates. The $dateDiff operator takes the parameters which are specified with the date values from the document along with the unit time. We also executed some examples where the $dateDiff operator is used in different cases to return the result within a unit period.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.