MongoDB Automation in Java

MongoDB Tutorial

MongoDB is an open source, NoSQL database that stores data in the form of documents. Being a NoSQL database, it is not relational and does not comply to ACID(Atomicity, Consistency, Isolation, Durability) properties.

  • Document - In mongoDB, data is stored in the form of documents, these are analogous to tuples/row in RDBMS. These documents contain data in the form of key-value pairs similar to JSON objects.
    	"_id" : ObjectId("5dfjsdd8d8fk3k9keb2d5d"), 
    	"FirstName" : "Kuldeep", 
    	"LastName" : "Rana", 
    	"Site" : "" 

  • Collection - Collections are analogous to tables in RDBMS and are collection of of a set of related documents (but the documents can have dissimilar fields).

MongoDB Commands

  • mongo --port <port>-
    To connect to a mongoDB in a specified port

  • use <dbName>-
    To select a database <dbName<

  • show dbs-
    To display all the databases

  • show collections-
    To display all the collections in the current database

  • db.<collectionName>.find()-
    To select all the data in the specified collection

  • db.<collectionName>.find({<key>:<value>})-
    To fetch data in the specified collection with the given condition (key-value pair)

  • db.<collectionName>.insert(<document>)-
    To insert given document in the specified collection

  • db.<collectionName>.update({<key>:<value>}, <document>)-
    Updates data for the given key-value pair with the provided document/key-value pairs

Sample Code for MongoDB automation in Java

In the following sample code we will connect to a mongoDB database, execute a find query and then assert the fetched result with expected value.

package com.artOfTesting.mongo;

import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import org.testng.Assert;

public class MongoAutomation{
   public static void main( String args[] ){
	//Connecting to the mongoDB instance
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	//Selecting the database
        DB db = mongoClient.getDB("dbName");
        //Selecting the collection
	DBCollection dbCollection = db.getCollection("collectionName");
	//Setting search query with the required key-value pair
	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.put("key", "value");
	//DBCursor with the find query result
	DBCursor cursor = dbCollection.find(searchQuery);
        //Fetching the response
	String response = null;			
	try {
	    while(cursor.hasNext()) {
	    response = response.concat(;
	finally { 
	//Asserting the fetched response with expected value
      catch(Exception e){