0

Given I have a collection with following documents:

{_id:..., job:..., time: 123192387231}

(time is time in milliseconds since 1970, unix time)

What would be the best way to retreive all documents which time is in the next 20 seconds to come?

In SQL I would do something like this:

SELECT * FROM X WHERE time-sysdate < 20 && time-sysdate > 0 

(Dates work with days in SQL I know :D)

ThatBrianDude
  • 2,952
  • 3
  • 16
  • 42
  • Add 20 seconds to the current time and supply them to the date range, [which you define just like the answers say](https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) – Neil Lunn Jun 28 '17 at 13:08
  • Is it really necessary though to cast them as Date objects? I feel like simply comparing two numbers differences would be a bit faster. EDIT: I would just need the current time in millieseconds if thats possible – ThatBrianDude Jun 28 '17 at 13:18
  • Easier if you save as MongoDate Objects else you have to multiply 1000 to get in milliseconds: NOW_MS = current_timestamp * 1000; Query: `{ "time": { $gt: }, "time": { $lte: +20000 } }` – Naga Penmetsa Jun 28 '17 at 14:03
  • var date = new Date(); var unixTime = date.getTime(); db.collection.aggregate([ { $redact: { $cond: { if: { $and:[ {$gt:[{$subtract:['$time',unixTime]},0]} ,{$lt:[{$subtract:['$time',unixTime]},20]} ]}, then: "$$DESCEND", else: "$$PRUNE" } } } ]) – Murugan Perumal Jun 28 '17 at 14:05

0 Answers0