I want to choose documents where from < now and to > (now + delay), where from, to and delay is document fields. Now is my variable.
something like that
{
from: {$gte: now},
to: {$lte: now + $delay}
}
The following query can get us the expected output:
db.collection.find({
"from":{
$gte: now
},
$expr:{
$lte:["$to", { $sum: ["$delay", now] }]
}
}).pretty()
var now = 2;
Data set:
{
"_id" : ObjectId("5d7645ab14e02904fe680e12"),
"from" : 2,
"to" : 4,
"delay" : 2
}
{
"_id" : ObjectId("5d7645ab14e02904fe680e13"),
"from" : 2,
"to" : 10,
"delay" : 2
}
{
"_id" : ObjectId("5d7645ab14e02904fe680e14"),
"from" : 6,
"to" : 10,
"delay" : 2
}
Output:
{
"_id" : ObjectId("5d7645ab14e02904fe680e12"),
"from" : 2,
"to" : 4,
"delay" : 2
}
$expr is not supportedIf you cannot use $expr you might consider $where.
NOTE: $where has a performance cost.
Example:
db.collection.find({
$where: function () {
return this.to > (now + this.delay);
}
});
this refers to the current document. You can also you obj to reference it.