MongoDB query for document older than 30 seconds

Nick Parsons picture Nick Parsons · Feb 6, 2014 · Viewed 13k times · Source

Does anyone have a good approach for a query against a collection for documents that are older than 30 seconds. I'm creating a cleanup worker that marks items as failed after they have been in a specific state for more than 30 seconds.

Not that it matters, but I'm using mongojs for this one.

Every document has a created time associated with it.

Answer

Friponneau picture Friponneau · Mar 19, 2014

If you want to do this using mongo shell:

db.requests.find({created: {$lt: new Date((new Date())-1000*60*60*72)}}).count()

...will find the documents that are older than 72 hours ("now" minus "72*60*60*1000" msecs). 30 seconds would be 1000*30.