Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Writing Complex MongoDB Queries Using QueryBuilder

DZone's Guide to

Writing Complex MongoDB Queries Using QueryBuilder

· Database Zone
Free Resource

What if you could learn how to use MongoDB directly from the experts, on your schedule, for free? We've put together the ultimate guide for learning MongoDBSign up and you'll receive instructions for how to get started!

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.

 

What if you could learn how to use MongoDB directly from the experts, on your schedule, for free? We've put together the ultimate guide for learning MongoDBSign up and you'll receive instructions for how to get started!

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}