Search code examples
mongodbmongodb-querymongodb-compass

MongoDB Compass : filter and query by date


Say I have a Travel collection that contains several documents,

Such as :

{
    "_id": {
        "$oid": "27637b4h6u7y897ba9021bn2"
    },
    "startTime": {
        "$date": "2021-05-04T13:55:38.286Z"
    }
    "stopTime": {
         "$date": "2021-05-04T11:55:38.286Z"
    }
}

{
    "_id": {
        "$oid": "2532b4h6u7y897ba9021bn2"
    },
    "startTime": {
        "$date": "2021-05-04T12:55:38.286Z"
    }
    "stopTime": {
         "$date": "2021-05-04T11:55:38.286Z"
    }
}

What query should I write, in mongoCompass if possible, to retrieve :

  • The number of travels longer than 1h?

Solution

  • You can use aggregation to get travel period grater then 1 hour

    You can use below aggregation code:

    [{$addFields: {
      travelTime: {$abs:{$subtract:[{ $toLong:'$stopTime'},{ $toLong:'$startTime'}]}}
    }}, {$match: {
      travelTime:{$gt:3600000}
    }}, {}]
    

    Here we are taking absolute time difference in milliseconds and checking if it's greater than one hour (3600000)