0

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}
}

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, but seems like I got lower version of mongodb where $expr is not supported
0

If 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.