[MongoDB]: Writing Complex queries Using QueryBuilder

Writing Complex MongoDB Queries Using QueryBuilder
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

rs1:PRIMARY> db.dbversit.insert({“_id” : 1,”fname” : “Srinivas”,”lname” : “Dbversity”,”marks” : [ {“MongoDB” : 48}, {“Oracle” : 49}, {“Cassandra” : 50}]})
rs1:PRIMARY> db.dbversit.insert({“_id” : 2,”fname” : “Hitardha”,”lname” : “Bayap”,”marks” : [ {“MongoDB” : 35}, {“Oracle” : 42}, {“Cassandra” : 37}]})
rs1:PRIMARY> db.dbversit.insert({“_id” : 3,”fname” : “Rajaroy”,”lname” : “Roy”,”marks” : [ {“MongoDB” : 45}, {“Oracle” : 41}, {“Cassandra” : 37}]})
rs1:PRIMARY>
rs1:PRIMARY> db.dbversit.find()
{ “_id” : ObjectId(“547861b66a3536c4fde39822”), “_id” : 1, “fname” : “Srinivas”, “lname” : “Dbversity”, “marks” : [ { “MongoDB” : 48 }, { “Oracle” : 49 }, { “Cassandra” : 50 } ] }
{ “_id” : ObjectId(“547861bb6a3536c4fde39823”), “_id” : 2, “fname” : “Hitardha”, “lname” : “Bayap”, “marks” : [ { “MongoDB” : 35 }, { “Oracle” : 42 }, { “Cassandra” : 37 } ] }
{ “_id” : ObjectId(“547861c06a3536c4fde39824”), “_id” : 3, “fname” : “Rajaroy”, “lname” : “Roy”, “marks” : [ { “MongoDB” : 45 }, { “Oracle” : 41 }, { “Cassandra” : 37 } ] }
rs1:PRIMARY>

If we want to get person whose last name is Dbversity and have obtained more than 35 marks in MongoDB then the MongoDB shell command for this will be –

rs1:PRIMARY> db.dbversit.find({$and:[{“lname”:”Dbversity”},{“marks.MongoDB”: {$gt:35}}]})
{ “_id” : ObjectId(“547861b66a3536c4fde39822”), “_id” : 1, “fname” : “Srinivas”, “lname” : “Dbversity”, “marks” : [ { “MongoDB” : 48 }, { “Oracle” : 49 }, { “Cassandra” : 50 } ] }
rs1:PRIMARY>

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”, “Dbversity”));
andQuery.add(new BasicDBObject(“marks.MongoDB”, 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(“Dbversity”).get(),
new QueryBuilder().start().put(“marks.MongoDB”)
.greaterThan(35).get()).get();

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

  • Ask Question