Hi,
I need assistance with performing aggregation on a timeseries collection in MongoDB 6. The collection structure includes fields like
{
"Timestamp": {
"$date": "2024-03-12T11:11:32.000Z"
},
"PointId": "12",
"Value": {
"$numberLong": "57"
}
}
query:
db.timeseriesCollection.aggregate([{
$match: {
"Timestamp": { $gte: ISODate("2023-02-01T00:00:00.000Z"), $lt: ISODate("2025-10-31T00:00:00.000Z") },
"PointId": "12"
}
},
{
$group: {
_id: {
PointId: "$PointId",
Timestamp: "$Timestamp"
},
startTimestamp: { $min: "$Timestamp" },
avg: { $avg: "$Value" },
}
},
{
$project: {
_id: 0,
id: "$_id.PointId",
intervalStart: "$_id.Timestamp",
avg: 1,
}
},
{
$sort: { intervalStart: 1 }
}
])
on this collection I want to aggregate data within a specified time range, such as from ‘2023-02-02T08:45:00.000Z’ to ‘2025-10-31T00:00:00.000Z’, and group it into intervals of different durations, such as minutely, hourly, daily, weekly, and yearly. For example, if the interval is set to monthly, I expect the output to include timestamps for each month within the range, starting from ‘2023-02-02T08:45:00.000Z’ and followed by
for eg:
2023-02-02T00:00:00.000Z
2023-03-02T00:00:00.000Z
2023-04-02T00:00:00.000Z
…
daily:
2023-02-02T08:45:00.000Z’
2023-02-03T00:00:00.000Z
2023-02-04T00:00:00.000Z
2023-02-05T00:00:00.000Z …
weekly:
2023-02-02T08:45:00.000Z
2023-02-05T00:00:00.000Z (Sunday as start of the week)
2023-02-12T00:00:00.000Z
2023-02-19T00:00:00.000Z …
I’ve attempted various solutions but haven’t achieved the desired results. Any assistance in crafting the MongoDB aggregation query would be greatly appreciated. Thank you!"