Learn to Add & Retrieve From a Collection using MongoDB & Java



In this chapter, we are going to use the MongoDB JDBC connection (created in the last article) in order to connect MongoDB database with JAVA. After successfully connecting MongoDB with JAVA, we are going to create a collection, insert documents into this collection and select this collection to display the retrieved documents through JAVA programming language.

MongoDB – Creation and Selection of a collection
In the last article, we were able to connect to MongoDB and the ‘testdb’ database present in the MongoDB. Now, we are going to create a ‘MyCollection1’ collection in the MongoDB in order to insert and select documents through JAVA Programming.


  • To create a collection, we can use the ‘createCollection ()’ method of com.mongodb.DB class.
  • To get or select a collection from the database, we can use the ‘getCollection ()’ method of com.mongodb.DBCollection class.
  • To insert a document into MongoDB, we can use the ‘insert ()’ method of com.mongodb.DBCollection class.


package com.eduonix.db;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoDBOperations {

	public static void main(String args[]) {
		try {
			/**** Connect to the MongoDB ****/
			MongoClient mongodb = new MongoClient("localhost", 27017);

			/**** Get database ****/
			// if database doesn't exists, MongoDB will create it for us
			DB db = mongodb.getDB("testdb");
			System.out.println("Connection to MongoDB database successfully");
			 * Creating and Inserting Records in MongoDB.
			DBObject dbObject = new BasicDBObject("title", "MongoDBTutorials").append("description", "No-SQL Database")
					.append("likes", 100000).append("url", "https://www.mongodb.com/").append("Tutorial", "Eduonix");

			db.createCollection("MyCollection1", dbObject);
			 * Selecting Records from MongoDB
			DBCollection coll = db.getCollection("MyCollection1");
			System.out.println("Collection has selected successfully");
			DBCursor cursor = coll.find();
			int index = 1;

			while (cursor.hasNext()) {
				System.out.println("Inserted Document: " + index);
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());

Before executing this program, make sure that the MongoDB instance is running on your local or remote machine. Here, the MongoDB instance is running on the local machine at port 27017.

Explanation of Code

  • Firstly, we are connecting to the MongoDB client through MongoClient class by passing the URL and port where MongoDB instance is running.
  • The MongoDB instance is returned in the mongodb instance variable. It is used to invoke DB instance through ‘mongodb.getDB (“testdb”)’ method into ‘db’ instance variable.
  • Next, we are creating instance of ‘DBObject’ through ‘BasicDBObject’ class that helps to create the schema definition to be inserted in the collection.
  • Next, we are creating collection through ‘db.createCollection (“MyCollection1”, dbObject);’ method.
  • Next, we are going to select this collection ‘MyCollection1’ through ‘db.getCollection (“MyCollection1”);’ method which returns the instance into ‘coll’ instance variable.
  • Through ‘coll’ instance variable, we can use ‘coll.insert (dbObject);’ to insert the DBObject instance which we have created before. At this step a document has successfully been added into the MongoDB.
  • Now, we are using ‘DBCursor’ class which returns the cursor to iterate over the documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method.
  • Lastly, with the help of ‘DBCursor’ instance, we are iterating over the available documents to display the document details which we had inserted in the last step into the collection ‘MyCollection1’.
  • The entire code is placed inside the try catch block in order to catch any possible exception thrown during runtime of this Java program.

When we execute above JAVA program, it will connect to the MongoDB and do the creation, selection and retrieving operations on the collection ‘MyCollection1’ as shown on the console.

Feb 04, 2017 4:04:39 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connection to MongoDB database successfully
Feb 04, 2017 4:04:39 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Feb 04, 2017 4:04:40 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:7}] to localhost:27017
Feb 04, 2017 4:04:40 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=2103123}
Feb 04, 2017 4:04:40 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:8}] to localhost:27017
Collection has selected successfully
Inserted Document: 1
{ "_id" : { "$oid" : "589641e8c8f5d929d86dfaa6"} , "title" : "MongoDBTutorials" , "description" : "No-SQL Database" , "likes" : 100000 , "url" : "https://www.mongodb.com/" , "Tutorial" : "Eduonix"}

This Java program will accomplish the following operations.

  • Connect to the MongoDB present at the localhost and port 27017.
  • Connect to the database ‘testdb’. If such database does not exist, then it will create a new database with this name.
  • Created a collection named as ‘MyCollection1’.
  • Selection of the collection named as ‘MyCollection1’.
  • Inserted a document into this collection.
  • The added document was retrieved and printed on the console with the help of ‘DBCursor’ class as shown in the above program.

Source code for the Blog: – Inserting and Retrieving

Conclusion: –
In this tutorial, we have created a JDBC connection to the MongoDB database. After JDBC connection, we have created a collection. Next, we selected this collection to insert a document followed by iterating over all the documents present in this collection in order to display the available documents present inside the collection on the console.


Please enter your comment!
Please enter your name here