Over a million developers have joined DZone.

Writing Complex MongoDB Queries Using QueryBuilder

· Database Zone

Learn NoSQL for free with hands-on sample code, example queries, tutorials, and more.  Brought to you in partnership with Couchbase.

MongoDB provides a lot of query selectors for filtering documents from a collection.  Writing complex queries for MongoDB in Java can be tricky sometimes.
Consider below data present in student_marks collection

{"sid" : 1,"fname" : "Tom","lname" : "Ford","marks" : [ {"english" : 48}, {"maths" : 49}, {"science" : 50}]}
{"sid" : 2,"fname" : "Tim","lname" : "Walker","marks" : [ {"english" : 35}, {"maths" : 42}, {"science" : 37}]}
{"sid" : 3,"fname" : "John","lname" : "Ward","marks" : [ {"english" : 45}, {"maths" : 41}, {"science" : 37}]}

If we want to get students whose last name is Ford and have obtained more than 35 marks in english then the MongoDB shell command for this will be -

     db.student_marks.find({$and:[{"lname":"Ford"},{"marks.english": {$gt:35}}]})

The same query written in Java will look something like this -

     DBObject query = new BasicDBObject();
     List<BasicDBObject> andQuery = new ArrayList<BasicDBObject>();
     andQuery.add(new BasicDBObject("lname", "Ford"));
     andQuery.add(new BasicDBObject("marks.english", new BasicDBObject("$gt", 35)));
     query.put("$and", andQuery); 

Using MongoDB QueryBuilder we can rewrite above query as -


    DBObject query = new QueryBuilder()
         .start()
         .and(new QueryBuilder().start().put("lname").is("Ford").get(),
             new QueryBuilder().start().put("marks.english")
                 .greaterThan(35).get()).get();


You can see that by using QueryBuilder we can write complex queries with ease. QueryBuilder class provides many methods like and, not, greaterThan, exists, etc. which helps in writing MongoDB queries more efficiently and less prone to error/mistakes.

 

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:
java ,nosql ,tips and tricks ,mongodb

Published at DZone with permission of Rishav Rohit, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}