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. 🙂
The problem with using the $where is that it can’t be indexed and there are currently issues with running javascript queries on the server, because the javascript engine is single threaded.
A better approach in this case would be to
re-write:t.lastRun < (NOW() – t.maxAge)
to: (t.lastRun + t.maxAge) < NOW()
The sum of t.lastRun and t.maxAge would be calculated and stored in an additional field upon insertion. Thus the resulting query would only require a single comparison.