Querying MongoDB Java Example

In the earlier post Mongodb java Hello World Example we have seen some basic operations on the MongoDB and searching the document was one of them there we had used find().In this post we will more focus on querying mongdb with java using find() method that is basically used for querying documents in mongodb collections. We will see that how we can use find() in different ways to meet our query needs.Below are the 4 basic scenarios that we are going to cover under querying mongodb java example.

  1. Fetching all the documents from a collection.
  2. Fetching a subset of documents from a collection.
  3. Fetching only selected keys of a document from a collection.
  4. Exclude some keys of a document from a collection.

Querying MongoDB with Java

For this example the document that we are using will have structure something like this , it has four keys firstName,lastName , founder and the wikilink.

{ 
  "firstName" : "rod", 
  "lastName" : "johnson", 
  "founder" :  "Spring", 
  "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29" 
}

Also I have a database with name lotusDB and it has a collection with name lotusCollection.
Note : For all the 4 cases I am using a Mongo Utility(MongoUtils.java) class that has a static method that will return the collection object. Code for that can be found at the end of post.

    1. Fetching all the documents from a collection : By default if we don’t pass any argument to find() function then it returns us all the documents present in that particular collection. If i execute below mentioned code then it will give me all the documents present in the lotusCollection“.
      DBCursor allResults = MongoUtils.getCollection().find();
      while(allResults.hasNext()){
         System.out.println(allResults.next());
      }

      Output :

{ "_id" : { "$oid" : "5349f2a46c363451e0c537a4"} , "firstName" : "rod" , "lastName" : "johnson" , "founder" : "Spring" , "wiki" : "http://en.wikipedia.org/wiki/Rod_Johnson_%28programmer%29"}
{ "_id" : { "$oid" : "5349f2a46c363451e0c537a5"} , "firstName" : "kevin" , "lastName" : "ryan" , "founder" : "mongo" , "wiki" : "http://en.wikipedia.org/wiki/Kevin_P._Ryan"}
{ "_id" : { "$oid" : "5349f2a46c363451e0c537a6"} , "firstName" : "james" , "lastName" : "gosling" , "founder" : "java" , "wiki" : "http://en.wikipedia.org/wiki/James_Gosling"}
{ "_id" : { "$oid" : "5349f2a46c363451e0c537a7"} , "firstName" : "doug" , "lastName" : "cutting" , "founder" : "Spring" , "wiki" : "http://en.wikipedia.org/wiki/Doug_Cutting"}
{ "_id" : { "$oid" : "5349f2a46c363451e0c537a8"} , "firstName" : "eliot" , "lastName" : "Horowitz" , "founder" : "mongo" , "wiki" : "http://en.wikipedia.org/wiki/Eliot_Horowitz"}
  1. Fetching a subset of documents from a collection :- Now instead of fetching all the documents from the collection we are interested in knowing the founder of MongoDB. For fetching all the documents matching our search criteria we have to pass this criteria as an argument in the find() method.
    BasicDBObject searchObject = new BasicDBObject();
    searchObject.put("founder", "mongo");
    DBCursor resultSubset = MongoUtils.getCollection().find(searchObject);
    while(resultSubset.hasNext()){
    	System.out.println(resultSubset.next());
    }

    Output :

    { "_id" : { "$oid" : "5349f2a46c363451e0c537a5"} , "firstName" : "kevin" , "lastName" : "ryan" , "founder" : "mongo" , "wiki" : "http://en.wikipedia.org/wiki/Kevin_P._Ryan"}
    { "_id" : { "$oid" : "5349f2a46c363451e0c537a8"} , "firstName" : "eliot" , "lastName" : "Horowitz" , "founder" : "mongo" , "wiki" : "http://en.wikipedia.org/wiki/Eliot_Horowitz"}

     

  2. Fetching only selected keys of a document from a collection : In our current document structure we have only 5 keys (including _id) , now assume if we have around 20 keys in the document and bringing all these keys back from the database as a part of our result set is a waste of our precious bandwidth and moreover it takes more time on the client side for decoding of documents (documents are stored in BSON format.) If we compare in SQL terms then we want to change our query from Select * to Select column_name.Now here we are interested in getting the first name and wiki links from all the documents of our search results.
    BasicDBObject searchObject = new BasicDBObject();
    searchObject.put("founder", "mongo");
    BasicDBObject fieldObject = new BasicDBObject();
    fieldObject.put("firstName", 1);
    fieldObject.put("wiki", 1);
    resultSubset = lotusCollection.find(searchObject,fieldObject);
    while(resultSubset.hasNext()){
        System.out.println(resultSubset.next());
    }

    Output :

    { "_id" : { "$oid" : "5349f2a46c363451e0c537a5"} , "firstName" : "kevin" , "wiki" : "http://en.wikipedia.org/wiki/Kevin_P._Ryan"}
    { "_id" : { "$oid" : "5349f2a46c363451e0c537a8"} , "firstName" : "eliot" , "wiki" : "http://en.wikipedia.org/wiki/Eliot_Horowitz"}


    To fetch the specific keys we had created a new BasicDBObject and put all the fields with value 1 that we want to fetch from our document. Notice that _id also came with our search by default , even it wasn’t requested. We can also exclude this field that we will see in next point.

  3. Exclude some keys of a document from a collection : In the previous example we have seen that ,we are getting the _id in our search result but we didn’t ask for it. find() method also provides you flexibility to exclude some of the fields that you don’t want in your search result. e.g we will exclude the _id from our search result.
    BasicDBObject searchObject = new BasicDBObject();
    searchObject.put("founder", "mongo");
    fieldObject = new BasicDBObject();
    BasicDBObject fieldObject.put("firstName", 1);
    fieldObject.put("wiki", 1);
    fieldObject.put("_id", 0);
    resultSubset = lotusCollection.find(searchObject,fieldObject);
    while(resultSubset.hasNext()){
    	System.out.println(resultSubset.next());
    }
    { "firstName" : "kevin" , "wiki" : "http://en.wikipedia.org/wiki/Kevin_P._Ryan"}
    { "firstName" : "eliot" , "wiki" : "http://en.wikipedia.org/wiki/Eliot_Horowitz"}

    Now if you see this time _id didn’t come with our resultset and that happened because we have set _id key value as 0 in the fieldObject.

Complete Code : MongoUtils.java

package com.lotusmedia.mongo;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class MongoUtils {

	private static final String DATABASE_NAME="lotusDB";
	private static final String COLLECTION_NAME="lotusCollection";
	private static MongoClient serverConnection = null;

	//TODO Thread Safety
	public static DBCollection getCollection() {
		if(serverConnection==null){
			try {
				serverConnection = new MongoClient("localhost",27017);
			} catch (UnknownHostException e) {
				e.printStackTrace();
				throw new RuntimeException("Not able to connect to localhost");
			}
		}		
		DB db = serverConnection.getDB(DATABASE_NAME);
		return db.getCollection(COLLECTION_NAME);
	}
}

FindMongo.java:

package com.lotusmedia.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;

public class FindMongo {

	public static void main(String[] args) {
	   //Fetch all the documents present in the collection.	
	   DBCollection lotusCollection=MongoUtils.getCollection("lotusCollection");
	   DBCursor allResults = lotusCollection.find();
	   while(allResults.hasNext()){
			System.out.println(allResults.next());
		}

	   //Fetch all the founders of mongodb.
	   BasicDBObject searchObject = new BasicDBObject();
	   searchObject.put("founder", "mongo");
	   DBCursor resultSubset = lotusCollection.find(searchObject);
	   while(resultSubset.hasNext()){
			System.out.println(resultSubset.next());
		}

	   //Fetch only firstname and wiki link
	   searchObject = new BasicDBObject();
	   searchObject.put("founder", "mongo");
	   BasicDBObject fieldObject = new BasicDBObject();
	   fieldObject.put("firstName", 1);
	   fieldObject.put("wiki", 1);
	   resultSubset = lotusCollection.find(searchObject,fieldObject);
	   while(resultSubset.hasNext()){
			System.out.println(resultSubset.next());
		}

	   //Fetch only firstname , wiki link and exclude _id
	   searchObject = new BasicDBObject();
	   searchObject.put("founder", "mongo");
	   fieldObject = new BasicDBObject();
	   fieldObject.put("firstName", 1);
	   fieldObject.put("wiki", 1);
	   fieldObject.put("_id", 0);
	   resultSubset = lotusCollection.find(searchObject,fieldObject);
	   while(resultSubset.hasNext()){
			System.out.println(resultSubset.next());
		}
	}

}


Disclaimer : All the above used images belong to their respective owners.


 

 

 

Let'sConnect

Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.
Let'sConnect

4 thoughts on “Querying MongoDB Java Example

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>