1

I would like to query a mongo collection with documents containing a field called last update time. Using javascript, I'd like to query all active devices and retrieve all documents that have a last update time of at least 2 hours. This is how I'm currently doing this:

    const Devices = await Devices.find({Status : "Active"});
            for(let i = 0; i < Devices.length; i++){
                let device = Devices[i];
                let today = new Date();
                // Comparison is in hrs  
                if(today.getHours() - device.LastUpdateTime.getHours() > 2)){
                // Additional Logic 
}
                

This works, but there are a lot of active devices so I'd like to specify my Mongo find. Is there a way to add this add the LastUpdateTime comparison within the Devices.find itself? LastUpdateTime is of type Date.

Any help would be appreciated.

ENV
  • 877
  • 2
  • 10
  • 32

1 Answers1

1

Assuming LastUpdateTime is a timestamp, something like this should work:

const twoHoursAgo = Date.now() - (1000 * 60 * 60 * 2);
const devices = await Devices.find({Status: 'Active', LastUpdateTime: {$lt: twoHoursAgo }})

More info: https://docs.mongodb.com/manual/reference/operator/query/lt/

If you've lots of documents, you'd probably want those properties indexed

divillysausages
  • 7,883
  • 3
  • 25
  • 39
  • How would I be able to this if LastUpdateTime is type Date? Currently if I do this, I get: "Error: Can't use $ls with Date" – ENV Apr 29 '21 at 20:13
  • It should just work (https://stackoverflow.com/a/25040692/639441) - make sure you're using `$lt`, or `$lte`, and not `$ls`. You're generally looking at dates in the ISO format - if your `LastUpdateTime` isn't stored like that, then it's going to be harder than it needs tob e – divillysausages Apr 29 '21 at 22:07
  • 1
    Thanks very much. I was using `$ls` rather than `$lt`. Now it's working – ENV Apr 30 '21 at 11:55