I am trying to perform a query which is composed of two $or‘s:
|--------------------
| Date1 | Date2 |
|--------------------
| NULL | NULL | *
| NULL | TODAY | *
| NULL | TOMRW |
| TODAY | TODAY | *
| TODAY | NULL | *
| TOMRW | NULL |
|--------------------
(I’ve marked the rows that would match with an asterisk)
(Date1 == null || Date1 <= today) && (Date2 == null || Date2 <= today)
I am not sure how to express this query in MongoDB.
It can be broken down into two individual queries that do exactly what they should:
{
"$or": [{
"Date1": {
"$exists": false
}
},
{
"Date1": {
"$exists": true,
"$lte": new Date("2012-01-07T04:45:52.057Z")
}
}]
}
and
{
"$or": [{
"Date2": {
"$exists": false
}
},
{
"Date2": {
"$exists": true,
"$lte": new Date("2012-01-07T04:45:52.057Z")
}
}]
}
Both of these select the correct set of documents – I just dont know how to execute them as a single query.
My initial thought was to do a query like this:
{
$and: [orQuery1, orQuery2]
}
Using an $and query returns 0 results. It was explained why here in this thread: $and query returns no result
Also in that thread, a suggestion was made to do a query like this:
{
Key: {valToMatch1: 1, valToMatch2: 2}
}
But I dont think an $or can be executed this way.
So, the question is: How do I construct my query such that I can combine the two $or’s into a single query?
(Its getting very late so I hope this question makes sense.)
first subquery
db.test.distinct(‘a’, {…});
second subquery
db.test.distinct(‘a’, {…});
unwind
query
this should work too (assume that ‘not exist’ and ‘null’ is the same)