I am doing a time series application (each document has a timestamp and a value) and need to aggregate values by grouping into time slots (intervals). To make the time slot, the timestamp is divided and then floored. For example a slot of 1-minute:
db.collection.aggregate([
{$project: {value:1, "timestamp": {$subtract: ["$time", new Date('1970-01-01')]}} },
{$project: {value:1, "time2": {$divide, ["$timestamp",60000]}}},
{$project: {value:1, "timeslot": {$floor: "$time2"}}},
{$group: {_id: "$timeslot", avg: {$avg, "$value"}}}
])
This did the job, but very clumsy: 3 $project in sequence, value:1 repeated each time. Is there a way to combine the $subtract, $divide, $floor... ?
Moreover, are there convenience methods in com.mongodb.client.model.Projections to do this? I am using Java mongodb-driver 3.6.2.