mongodbmongodb-queryaggregation-frameworkaggregation

Data type conversion in mongodb version 3.6


I am using the MongoDB version 3.6. In one of my collection I have two fields one is in unix timestamp and another is in date. In the aggregation pipeline I want to calculate the difference between these two fields. In version 4.0 and above mongo provides few functions which can convert data type like $toInt, $toLong,etc. but those functions are not available in the version 3.6. Is this possible and if it is, then how to do it?


Solution

  • You can simply $subtract the 2 dates. You will get the date difference in milliseconds.

    db.collection.aggregate([
      {
        "$addFields": {
          "dateDiff": {
            "$subtract": [
              ISODate("2020-12-08"),
              "$date"
            ]
          }
        }
      }
    ])
    

    Here is Mongo playground for your reference