torbenrudgaard
torbenrudgaard

Reputation: 2561

Building your MongoDB $match as a string dynamically

Im trying to build my $match dynamically for my MongoDB request, and when I do the simple stuff it works perfect, like this:

var matchStr = {};
matchStr.status = { "$lte": 3 };
matchStr.checkout = { $gte: Math.round(new Date(d).getTime()/1000) }

And then I run the

bookingTable.aggregate([
    {
        $match: {
            $and: [ matchStr ]
        }
    }, etc....

Which gives a nice:

matchStr: {
    "status": {
        "$lte": 3
    },
    "checkout": {
        "$gte": 1527669588
    }
}       

So thats all great, but what if I want to put something like this into the matchStr...

{ $or: [ { "managerDate": {$lte: managerLast} },  { "activityDate": {$lte: activityLast} } ] }
,
{ $or: [ { "expireDate":  {$gt: oneDayBackward} }, { "status": {$lt: 9}} ] }
,
{ "status": { $in: [0, 1, 2, 9 ] } }

How can I do that?

Upvotes: 1

Views: 44

Answers (1)

Ashh
Ashh

Reputation: 46481

There are multiple syntax for accessing the property of an object

var matchStr = {}
matchStr.status = { "$lte": 3 }
matchStr.checkout = { "$gte": Math.round(new Date().getTime()/1000) }

matchStr["$or"] =  [
  { "managerDate": { "$lte": "managerLast" }},
  { "activityDate": { "$lte": "activityLast" }}
]

or If you want to push to $or operator

matchStr["$or"].push({ "managerDate": { "$lte": "managerLast" } })
matchStr["$or"].push({ "activityDate": { "$lte": "activityLast" } })

Upvotes: 1

Related Questions