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

Read the 2019 State of Database DevOps Report for the very latest insights

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.

 

Read the 2019 State of Database DevOps Report for latest insights into DevOps adoption among SQL Server professionals, and the benefits and challenges of including the database in DevOps initiatives

Topics:
java ,nosql ,tips and tricks ,mongodb

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}