How can I build an $or query for MongoDB using the Java driver?
Asked Answered
O

2

39

I'm trying to Or some conditions in MongoDB (using the Java driver). This is what I'm doing :

Pattern regex = Pattern.compile("title");   
DBCollection coll = MongoDBUtil.getDB().getCollection("post_details");

BasicDBObject query = new BasicDBObject();
query.put("category_title", "myCategory");      
query.append("post_title", regex);  
query.append("post_description", regex);    

DBCursor cur = coll.find(query);
while(cur.hasNext()) {
    System.out.println(cur.next().get("post_id"));
}

I'd like to use the $or operand on these conditions, but I guess the default is "and" and I don't know how to change it. In the above code if one of the conditions returns null, the result will be null too.

Orabelle answered 16/5, 2012 at 14:31 Comment(3)
'code' query.append("$or", new BasicDBObject().append("post_title", regex).append("post_description", regex))Nieman
That doesn't look right. $or clauses are wrapped by an array not an object.Premonish
guys please answer my question https://mcmap.net/q/409348/-writing-mongodb-syntax please i need your help >_<Ondometer
P
74

You are correct that the "default" for specifying multiple field in a query is that each field serves as a conditional filter, and thus is an AND operation.

You can perform MongoDB queries with an OR clause by using the $or operand which has the following syntax :

db.col.find({$or:[clause1, clause2]})

Where each clause can be a query. $or does not have to be a top level operand but if it is MongoDB can use an index for each seperate clause.

In your example you want to end up with this query :

db.col.find({$or:[{"post_title", regex}, {"post_description", regex}]});  

Which can be constructed in Java through :

DBObject clause1 = new BasicDBObject("post_title", regex);  
DBObject clause2 = new BasicDBObject("post_description", regex);    
BasicDBList or = new BasicDBList();
or.add(clause1);
or.add(clause2);
DBObject query = new BasicDBObject("$or", or);
Premonish answered 16/5, 2012 at 14:56 Comment(3)
thnx , let me test it and get back 2 u . :)Orabelle
I tried this approach in MongoDB 3.2 with Java driver 3.2.2 and I get the error: Can't resolve the method dbColl.find(DBObject). Can you, please, update the answer for the actual Java driver version.Baldridge
Please, have a look at #36753754Baldridge
O
13

With filters you could build yours like:

import com.mongodb.client.model.Filters;
...

Bson filter = Filters.or(
                    Filters.eq("post_title", regex), 
                    Filters.eq("post_description", regex)
                  );
Optimist answered 18/11, 2016 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.