Querying MongoDB with nested logical operators

681 views
Skip to first unread message

Banks

unread,
Apr 4, 2012, 7:57:17 AM4/4/12
to mongodb-user
Need to query MongoDB with nested logical operators using the Mongo
Driver Java API/Spring Templates.
What i have experienced is that MongoDB tends to group all the ORs &
ANDs together.
Example : What i need is
(Condition A OR Condition B OR Condition C )
And
(Condition D OR Condition E OR Condition F )
And
Condition G


results in
Condition A OR Condition B OR Condition C OR Condition D OR Condition
E OR Condition F
AND Condition G





Banks

unread,
Apr 4, 2012, 8:24:11 AM4/4/12
to mongodb-user
I am using the QueryBuilder to build my query.

Here's the pseudo code.

QueryBuilder queryBuilder = new QueryBuilder.start();
queryBuilder.OR(QueryBuilder.start(Condition A.get());
queryBuilder.OR(QueryBuilder.start(Condition B.get());
queryBuilder.OR(QueryBuilder.start(Condition C.get());

queryBuilder.put(QueryBuilder.start(Condition G);

queryBuilder.OR(QueryBuilder.start(Condition D.get());
queryBuilder.OR(QueryBuilder.start(Condition E.get());
queryBuilder.OR(QueryBuilder.start(Condition F.get());

Dan Crosta

unread,
Apr 4, 2012, 10:12:45 AM4/4/12
to mongodb-user
QueryBuilder doesn't support $and, so you'll need to use an explicit
BasicDBObject and BasicDBList to do this. Something like:

BasicDBList andClauses = new BasicDBList();
andClauses.add(
QueryBuilder.start().or(
QueryBuilder.start("foo").is("a").get(),
QueryBuilder.start("foo").is("b").get()).get()
);
andClauses.add(
QueryBuilder.start().or(
QueryBuilder.start("bar").is("c").get(),
QueryBuilder.start("bar").is("d").get()).get()
);

BasicDBObject query = new BasicDBObject();
query.put("$and", andClauses);

should do the trick.

- Dan

Banks

unread,
Apr 12, 2012, 9:50:39 AM4/12/12
to mongodb-user
Dan, group,

I intend to use the spring API with the nestsed query.
The query suggested works well with mongo driver.
What I want is the dao or the mapped object being returned rather than
the DBObject which I then have to write a custom converter for.
> > > Need to query MongoDB withnestedlogicaloperators using the Mongo

Sam Millman

unread,
Apr 12, 2012, 10:06:51 AM4/12/12
to mongod...@googlegroups.com
Your looking for: https://jira.mongodb.org/browse/SERVER-828

Its not far off.

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


Reply all
Reply to author
Forward
0 new messages