How to write complex mongodb query using QueryBuilder
Posted By : Md Qasim Siddiqui | 01-Jun-2015
This blog will describe how to write complex queries using Query Builder. I have build Custom Query Builder for search engine purpose. So i will show step by step.
Step 1
Create Service method with map as arguments having keyvalue pair for search engine parameters
public List searchUsers(Map map){
return searchDao.searchUsers(map);
}
Step 2
Create Dao method
public List searchUsers(Map map){
return searchDao.searchUsers(map);
}
Step 3
public DBCollection getDBCollection(String collectionName){
try {
return datasource.mongo().getDB(datasource.getDatabaseName()).getCollection(collectionName);
} catch (Exception e) {
// TODO Auto-generated catch block
// throw exception
}
}
Step 4
public QueryBuilder mongoQueryBuilder(Map map){ Iterator> it = map.entrySet().iterator(); QueryBuilder queryBuilder = QueryBuilder.start(); while(it.hasNext()){ Entry keyValue = it.next(); if(!isInteger(keyValue.getValue())) queryBuilder.and(keyValue.getKey().trim()).regex(Pattern.compile(keyValue.getValue().trim()+".*",Pattern.CASE_INSENSITIVE)); else queryBuilder.and(keyValue.getKey().trim()).is(Integer.parseInt(keyValue.getValue())); } return queryBuilder; }
Step 5
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
Step 6
create class datasource
@Configuration
public class Datasource extends AbstractMongoConfiguration{
@Override
public String getDatabaseName() {
return "samepinch";
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1");
}
}
In Step 4 I have created QueryBuilder according to my need of search engine you can customized this mongo QueryBuilder method code to build query according to your requirment. Hope this blog may help you.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Md Qasim Siddiqui
Qasim is an experienced web app developer with expertise in groovy and grails,Hadoop , Hive, Mahout, AngularJS and Spring frameworks. He likes to listen music in idle time and plays counter strike.