Ele
Ele

Reputation: 33726

How to calculate howmany elapsed milliseconds into a range of date

I have a problem to make a selection using new Date() and a Date attribute in a specific collection.

For example, this is a collection with a document:

{_id: ObjectId(12345), 'last_execution': ISODate("2016-12-12T11:35:44.832Z")}

I want to fetch documents where since last_execution to now have passed 15 minutes.

I can do this using $where and functions as follow:

db.collection.find( { $where: function() { return ((new Date().getTime() - this.last_execution.getTime()) >= (15 * 60 * 1000) ) } } )

But according to MongoDB's documentation this way the indexes won't be used.

Any ideas?

Thank you!

Upvotes: 1

Views: 210

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311935

Calculate the time of 15 minutes ago and then query for the docs that are older than that time.

var cutoff = new Date();
cutoff.setMinutes(cutoff.getMinutes() - 15);
db.collection.find({last_execution: {$lte: cutoff}})

Upvotes: 2

Related Questions