Combining multiple $or conditions with AND

4,953 views
Skip to first unread message

Mikael Nousiainen

unread,
Aug 12, 2010, 4:14:01 AM8/12/10
to mongodb-user
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

Michael Dirolf

unread,
Aug 12, 2010, 3:02:30 PM8/12/10
to mongod...@googlegroups.com
In addition to waiting for $and, you could imagine translating queries
like the one you have into a different form than what you're using.
So:

(A || B) && (C || D)

becomes

((A || B) && C) || ((A || B) && D)

becomes

(A && C || B && C) || (A && D || B && D)

becomes

A && C || B && C || A && D || B && D

the last form is supported by the current query language.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

Brian

unread,
Aug 24, 2010, 10:07:25 PM8/24/10
to mongodb-user
Wouldn't this query work for drivers that aren't using a hashmap for
BSON objects? IE: a driver that actually sent the two fields of the
same name to the server? :

db.test.find({
a : {$in : [10, 11]},
a : {$in : [12, 13]}
});

Michael Dirolf

unread,
Aug 25, 2010, 12:01:13 PM8/25/10
to mongod...@googlegroups.com
In some cases that sort of thing can work currently - but not really
supported or guaranteed to work long term.

Reply all
Reply to author
Forward
0 new messages