From MongoDB version >= 4.4 you can use the $function operator to define custom functions to implement behavior not supported by the MongoDB Query Language. Logic to add two time-data in HH:MM:SS
format is taken from here.
So try this query:
db.testCollection.aggregate([
{
$group: {
_id: "$id",
times: { $push: "$duration" }
}
},
{
$project: {
_id: 1,
totalDuration: {
$function: {
body: function(times) {
let hours = 0;
let minutes = 0;
let seconds = 0;
for (let i = 0; i < times.length; i++) {
let values = times[i].split(":");
hours += parseInt(values[0]);
minutes += parseInt(values[1]);
seconds += parseInt(values[2]);
}
let realHrs = hours + Math.floor(minutes / 60);
let realMins = (minutes % 60) + Math.floor(seconds / 60);
let realSecs = seconds % 60;
return realHrs + ":" + realMins + ":" + realSecs
},
args: ["$times"],
lang: "js"
}
}
}
},
{
$sort: { _id: 1 }
}
]);
Output
/* 1 */
{
"_id" : "1",
"totalDuration" : "15:6:12"
},
/* 2 */
{
"_id" : "2",
"totalDuration" : "7:30:0"
}
Data in testCollection
collection:
{
"_id" : ObjectId("..."),
"id" : "1",
"duration" : "07:30:30"
},
{
"_id" : ObjectId("..."),
"id" : "1",
"duration" : "07:35:42"
},
{
"_id" : ObjectId("..."),
"id" : "2",
"duration" : "07:30:00"
}