sample data.
"id": 1
"createdAt": {
"$date": "2020-09-29T01:52:10.199Z"
},
"updatedAt": {
"$date": "2020-09-29T02:55:10.199Z"
}
"id": 2
"createdAt": {
"$date": "2020-09-29T01:52:10.199Z"
},
"updatedAt": {
"$date": "2020-09-29T01:55:10.199Z"
}
Code:
db.orders.aggregate([
{
$project: {
products: 1,
dateDifference: {
$subtract: [ "$createdAt", "$updatedAt" ]
}
}
},
{
$unset: "_id"
}
])
Output:
"id": 1
"createdAt": {
"$date": "2020-09-29T01:52:10.199Z"
},
"updatedAt": {
"$date": "2020-09-29T01:55:10.199Z"
}
timeDifference: -695752959
Expected Output
"id": 1
"createdAt": {
"$date": "2020-09-29T01:52:10.199Z"
},
"updatedAt": {
"$date": "2020-09-29T01:55:10.199Z"
}
timeDifference: 1 hr 3 minutes / 1:03:00 any of the 2
"id": 2
"createdAt": {
"$date": "2020-09-29T01:52:10.199Z"
},
"updatedAt": {
"$date": "2020-09-29T01:55:10.199Z"
}
timeDifference: 3 minutes / 0:03:00 any of the 2
averageDiff: 30 minutes // sample
I want to get the time difference for my createdAt and updatedAt fields and get the average of the time so that I can display on my MongoDB charts. Any suggestsions on how to do it?
The best you can have this
It results in hours. By changing the number, you can have it in days/seconds. Default you get milliseconds.