I need to combine multiple $or conditions with an AND condition
to create a query for multiple date ranges. However, due to the
nature of JavaScript / JSON language in MongoDB, only
one $or condition is used as "$or" is the key in the map
of key-value pairs.
Is there any other way of doing such queries (or an explicit way
of expressing an AND condition). I found a ticket about
an explicit $and operator, but that has not been implemented yet:
http://jira.mongodb.org/browse/SERVER-1089 .
The main reason for this kind of queries is that I'm generating
the queries dynamically from another application based
on criteria entered by the user.
Here are the queries that I've been trying:
db.test.find( {
$or : [
{ "birthdate" : { $gte : new Date(1975, 1, 1) },
"birthdate" : { $lte : new Date(1980, 1, 1) } },
{ "birthdate" : { $gte : new Date(1985, 1, 1) },
"birthdate" : { $lte : new Date(1990, 1,
1) } } ] }).count();
-> works as expected
db.test.find( {
$or : [
{ "birthdate" : { $gte : new Date(1975, 1, 1) },
"birthdate" : { $lte : new Date(1980, 1, 1) } },
{ "birthdate" : { $gte : new Date(1985, 1, 1) },
"birthdate" : { $lte : new Date(1990, 1, 1) } } ],
$or : [
{ "postalCode" : { $gte : 10000 },
"postalCode" : { $lte : 20000 } },
{ "postalCode" : { $gte : 40000 },
"postalCode" : { $lte : 50000 } } ] } ).count();
-> only includes the latter $or in the query