Error while grouping the data to calculate the average

db.alert_notification.aggregate([{
    $match: {
         created_date: {
                $gte: ISODate("2020-02-24T00:00:00.000Z"),
                $lt: ISODate("2020-08-25T00:00:00.000Z")
            }
        }
    },{
        $project: {
            resolved_date: 1,
            device_date_time_stamp: 1,
            dateDifference: {$divide : [ { $subtract: ["$resolved_date" ,"$device_date_time_stamp"] }, 1000 * 60 * 60] }
        }
    }
    ,{
        $group: {
            _id: null,
            
            dateDifference1: { 
                $sum: "$dateDifference"
            }
        }
    }
   
]);

//ERROR

{
	"message" : "cant $subtract adate from a string",
	"ok" : 0,
	"code" : 16556,
	"codeName" : "Location16556",
	"name" : "MongoError"
}

Hello, @97vaqasazeem_N_A!

It looks like your $device_date_time_stamp property contains data of type string, but you’re trying to use it as a date type.

You can debug your data-types with an aggregation like this:

db.alert_notification.aggregate([
  {
    $project: {
      typeA: {
        $type: '$resolved_date',
      },
      typeB: {
        $type: '$device_date_time_stamp',
      },
    },
  },
]);

You can try to convert your data types on the fly, using $toDate pipeline operator:

/* ... */
{ 
  $subtract: [
    {
      toDate: '$resolved_date',
    }, 
    {
      toDate: '$device_date_time_stamp',
    },
  ] 
}
/* ... */

Though, it is always better to have a consistent data types across documents - this way you will be able to write your aggregations more easily, and they will perform better :wink: