I have mongo collection with data records coming from gps device in every 2-3 second, data sample is as shown here
1. {imei:123456.., port:8000,createdon:timestamp, updatedon : timestamp}
2. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
3. {imei:123456.., port:8000,createdon:timestamp, updatedon : timestamp}
4. {imei:323456.., port:8000,createdon:timestamp, updatedon : timestamp}
5. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
6. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
7. {imei:323456.., port:8000,createdon:timestamp, updatedon : timestamp}
... around 2 billion records
my requirement is to create aggregate query to find all imei
s for which time difference between 2 consecutive records is >= given time in minutes for a particular date time.
like for imei:223456..
above records will be as below:
- a. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
- b. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
- c. {imei:223456.., port:8000,createdon:timestamp, updatedon : timestamp}
if for a given date time these records are considered then
time diff b.createdon - a.createdon
=> let say 2 min similarly c.createdon - b.createdon
= 3 min
if given time is 3 minutes then imei:223456..
is considered as there is a matching time difference record, otherwise it is dropped from the output.
I have tried query as following but its not giving the correct result
collection
.aggregate([{
$match: {
"createdon": // filter out all items that are inside a range
{
$gte: start_dt,
$lte: end_dt
}
}
},
{
$group: {
_id: "$imei",
max_time: {$max: "$createdon"},
min_time: {$min: "$createdon"}
}
},
{
$set: {
difference: {
$divide: [{$subtract: ["$max_time", "$min_time"]}, 60 * 1000]
} // get difference in minutes
}
},
{
$match: { // filter out all items that are having difference >= 3 min or any given time
difference: {$gte: minutes}
}
}
]);
request params start_dt= new Date('02-24-2023').getTime()
, end_dt= new Date('02-25-2023').getTime()
, and time diff minutes = 3
, as a result I should get all IMEIs for those any 2 consecutive records difference is exceeding given time 3 min