Reputation: 1901
Document structure (fields unrelated to this question removed):
{
_id: ObjectId,
lastDate: Date,
interval: Integer, // in seconds
mode: String
}
What I'm looking for is a query similar to:
{
lastDate: {
$lt: new Date() - $interval
},
mode: {
$in: ['collect', 'debug']
}
}
Therefore the query would get all documents with a lastDate
that's less than the current date/time minus its own interval. Also only get documents with mode set to collect or debug.
Can this be done with a basic query or do I need to use aggregate or mapReduce?
Upvotes: 0
Views: 440
Reputation: 11671
Mathematically, your condition is
lastDate < current_time - interval
which is equivalent to
lastDate + interval < current_time
Therefore, instead of (or in addition to) storing lastDate
and interval
, store their sum. The sum can be stored as seconds since epoch or as a date - you can pick what's most convenient for you in your client code.
Upvotes: 1
Reputation: 1901
I found a solution but I'm not sure if it's the best one performance-wise.
The query that works:
{
$where: "this.lastDate < new Date() - this.interval",
mode: {
$in: ['collect', 'debug']
}
}
Uses the $where
operation:
Use the
$where
operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The$where
provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection. Reference the document in the JavaScript expression or function using eitherthis
orobj
.
Upvotes: 0