Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb: Query document based on calculation for each document

Tags:

mongodb

I want to query a document from a MongoDB database where the condition is the outcome of a given calculation. I don't know if this is understandable, an analog SQL query might help:

SELECT * FROM tasks AS t WHERE t.lastRun < (NOW() - t.maxAge)

Each tasks has a maxAge field which determines how often a task should run. If the maxAge is reached, the query should return that task which is then executed.

Because I lack the vocabulary to describe such a query it's hard to find anything about this topic. Please be forgiving if this is mentioned somewhere. :-)

My first reflex was: Let's map the whole collection to contain the calculated threshold for each task, but this seems a bit too much for such a simple query. I hope this isn' t the only solution to this. :-)

like image 981
Malax Avatar asked Mar 23 '26 01:03

Malax


1 Answers

You could try

db.tasks.insert({lastRun:new ISODate(), maxAge:100});

db.tasks.find({ $where: "this.maxAge < (new ISODate()-this.lastRun)"});
like image 86
Skynet Avatar answered Mar 26 '26 02:03

Skynet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!