I want to filter the objects which will go into an aggregate chain by only working on the latest entries defined by a timestamp.
Currently I use new Date().getTime() - (1000 * 60 * 5) in the $match to find all entries within the last 5 minutes.
Working example
(fetchedAtTime is a unix timestamp)
db.getCollection('data').aggregate([
{ $match: {"fetchedAtTime": {$gte: new Date().getTime() - (1000 * 60 * 5)}} },
{ $group: {
_id: "$name",
latestFetchedAtTime: {$max: "$fetchedAtTime"},
oldestFetchedAtTime: {$min: "$fetchedAtTime"}
}}
]);
Problem
But I don't want to use new Date(). I want to subtract the 5 minutes from the most resent fetchedAtTime entry (for cases when the are no new entries added to the database for whatever reason).
So I tried to add the $max into the $match but none of my tries were successful.
Non working example(s)
(I've put all $matches in one code block just for readability - tried them separately)
db.getCollection('data').aggregate([
{ $match: {"fetchedAtTime": {$gte: { $subtract: [{$max: "$fetchedAtTime"}, (1000 * 60 * 5)]}}} },
{ $match: {"fetchedAtTime": {$gte: { $subtract: [new Date({$max: "$fetchedAtTime"}).getTime(), (1000 * 60 * 5)]}}} },
{ $match: {"fetchedAtTime": {$gte: new Date({$max: "$fetchedAtTime"}).getTime() - (1000 * 60 * 5)}} },
{ $group: {
_id: "$name",
latestFetchedAtTime: {$max: "$fetchedAtTime"},
oldestFetchedAtTime: {$min: "$fetchedAtTime"}
}}
]);
Is there a way to archive this in one aggregate chain?