Java Data Base Connectivity (JDBC) with MongoDB

Lets first start with some basics of MongoDB.

What is MongoDB?

MongoDB is document-oriented NoSQL database. This is a collection of documents where data is stored in the form documents, unlike old SQL systems where data is stored in the form of tables. Here each document consists of the key-value pairs which are the building block of the NoSQL database. The data is stored in documents in the key-value pairs. 

example:

{

"first_name":"Ambarish",
"last_name" :"Dashora"
}

So basically the data is stored in the JSON format called documents in MongoDB.

Now we are here to connect, create, access, and modify collections and documents of MongoDB using java. So let's get started. First of all, we will learn how to set up a MongoDB client driver for java. I am assuming that you have installed MongoDB on your system. If not then download and install it from this link:  MongoDB.

Get MongoDB client driver:

    To get the client driver of MongoDB go to this link and download: MongoDB Client the "mongo-java-driver-3.12.3.jar" file of MongoDB client. Save it to your working directory or any directory you want but just keep in mind to include that directory to your classpath while compiling and executing the java code.
    In the C directory create a folder structure: C:\data\db.  All the databases will be stored in 'db' folder by MongoDB.
    Now we are all set to write our first code of creating a document in MongoDB using java.

    Program 1: To create a database, collection, and document:

    • Connect to MongoDB Server

    First of all, connect to the MongoDB server. MongoDB server listens to requests by default on 27017 port number. Here our host will be localhost. To connect to the server we will create an object of MongoClient class.

    MongoClient mongoClient=new MongoClient("localhost",27017);
    • Get the object of the database
    To access the database we will call method getDB() and pass the name of the database to this function of MongoClient class. It will return the reference of DB class object. Here the database name you have passed if it does not exist then it will create that database automatically. 

    DB db=mongoClient.getDB("testDB");
    
    • Get collection from the database
    Now get the collection in the database for this will call getCollection() method of DB class and pass the name of collection and  if the passed argument of name of collection does not exist then it will create that one in the given database automatically.

    DBCollection students=db.getCollection("students");
    
    • Create a document object.
    Now to create the document, create the object builder by calling static start() method of BasicDBObjectBuilder class, this method will return the address of this class.

    BasicDBObjectBuilder objectBuilder = BasicDBObjectBuilder.start();
    
    • Append key-value pair in the document object
    Append the key-value pair for a document in the collection. Every document in a collection must have a unique key with the name '_id' if the user doesn't create one explicitly then MongoDB will create a unique id implicitly. Code to append is as below: 

    objectBuilder.append("_id",id); 
    objectBuilder.append("firstName",firstName);
    objectBuilder.append("lastName",lastName); 
    • Get the document 
    Get the instance of DBObject from Object builder.

    DBObject document=objectBuilder.get();
    
    • Insert the document in the collection.
    With reference to the collection, insert the document in the collection.

    students.insert(document);
    

    Now the complete code will look like this:

    Example1.java

    import com.mongodb.*;
    class Example1
    {
      public static void main(String arg[])
      {
    	int id=111;
    	String firstName="Ambarish";
    	String lastName="Dashora";
    	MongoClient mongoClient=new MongoClient("localhost",27017);
    	DB db=mongoClient.getDB("testDB"); 
    	DBCollection students=db.getCollection("students");  
    	BasicDBObjectBuilder objectBuilder=BasicDBObjectBuilder.start(); 
    	objectBuilder.append("_id",id); 
    	objectBuilder.append("firstName",firstName);
    	objectBuilder.append("lastName",lastName);
    	DBObject document=objectBuilder.get();
    	System.out.println(document);
    	students.insert(document);
    	mongoClient.close();
       }
    }

    To compile the above code we will have to specify the location in the classpath, where we have stored the jar file as discussed above.

    To compile:- javac -classpath c:\location to the jar file Example1.java

    To execute this program we must first make sure that the MongoDB server is running or not. If during installation you have checked the checkbox to run as service then your server will be running otherwise you will have to execute mongod.exe file located at the place where you have installed your MongoDB  server in  my case it is this :

      "C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"

    It is default installation location.

    So now the server is running and you need to execute the program to insert a document in the collection. For this, we will type the following command:

    java -classpath c:\location to the jar file Example1

    So that's done we have finally inserted the document in the collection. As you can see we neither had testDB named database nor students named collection and both of them got created and the document got inserted in the collection after the execution of the above program.

     Program 2: To get all the documents of a collection:

    To get all the documents of the collection, the first three steps are the same as above, but there is a difference in the next steps.

    • Get the cursor object
    To get all documents, we will call the  find() method of collection class through its reference. It will return the reference of  DBCursor class.

    DBCursor cursor=students.find();

    • Iterate and get all documents
    Now with the reference DBCursor object we will call two methods hasNext()  which will return true or false i.e whether the next document is present or not and next() which will return each document in JSON form, these two methods will provide us all documents in the collection. 

    while(cursor.hasNext())
    {
    System.out.println(cursor.next());
    }
    

    Now the complete code will look like this:

    Example2.java

    import com.mongodb.*;
    class Example2
    {
     public static void main(String ar[])
     {
      MongoClient mongoClient=new 
      MongoClient("localhost",27017);
      DB tmdb=mongoClient.getDB("testDB");
      DBCollection st 
      sudents=tmdb.getCollection("students");
      DBCursor cursor=students.find();
      while(cursor.hasNext())
      {
       System.out.println(cursor.next());
      }
      mongoClient.close();
     }
    }
    

    Program 3: To delete a document from the collection:

    To delete a document from the collection all the steps of example one will remain the same except the last step where instead of inserting a document we will call remove the method of DBCollection class to remove a document. Here, instead of appending all the key-value pairs, we will append only one through which we want to delete the document and all the documents with the specified value of the key is there will get deleted ex: Suppose we append "firstName" as "Binod" ๐Ÿ˜‚ then all the documents with first name Binod will get deleted.

    Example3.java

    import com.mongodb.*;
    class Example3
    {
     public static void main(String aa[])
     {
      MongoClient mongoClient=new MongoClient("localhost",27017);
      DB db=mongoClient.getDB("testDB");
      DBCollection students=db.getCollection("students");
      BasicDBObjectBuilder objectBuilder=BasicDBObjectBuilder.start();
      objectBuilder.append("firstName","binod");
      DBObject query=objectBuilder.get();
      students.remove(query);
      mongoClient.close();  
     }
    }
    

    Program 4: To update a document in the collection:

    To update a document we have to create two DBObjects one is for query another is updated document i.e first object will contain the unique key-value pair which will let the function know which document we want to update and the second object will be a new document which has all updated key-value pairs,  and then there is an update method in the collection class to which we will pass both the objects and it will update the document in the collection.

    Example4.java

    import com.mongodb.*;
    class Example4
    {
     public static void main(String a[])
     {
      MongoClient mongoClient=new MongoClient("localhost",27017);
      DB db=mongoClient.getDB("testDB");
      DBCollection students=db.getCollection("students");
      BasicDBObjectBuilder documentBuilder=BasicDBObjectBuilder.start();
      documentBuilder.append("_id",113);
      documentBuilder.append("firstName","Binod");
      documentBuilder.append("lastName","Kumar");
      DBObject document=documentBuilder.get();
    
      BasicDBObjectBuilder queryBuilder=BasicDBObjectBuilder.start();
      queryBuilder.append("_id",113);
      DBObject query=queryBuilder.get();
      students.update(query,document);
      mongoClient.close();
     }
    }
    


    So this is how we can perform some basic operations on the MongoDB database. Hope you liked this article and it would have helped you in understanding how to access MongoDB databases using java.

    Thanks for reading 
    Happy coding๐Ÿ˜€๐Ÿ˜€





    Comments

    Post a Comment

    Popular posts from this blog

    PROJECT-2 Picture Modifier

    PROJECT 1 DerbyDB Creator -SQL scripting tool for Apache Derby