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

血红的双手。 提交于 2019-11-28 05:17:32

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);

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)
                  );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!