Signup/Sign In

JDBC MongoDB Connectivity

In this tutorial, we are going to discuss database connectivity between Java application and MongoDB. MongoDB is a document based database that is used to store data into JSON format rather than table or relation. It is completely different from the relational database like: mysql. You can get idea of MondoDB from our latest tutorial here MongoDB Tutorial.

Now lets start to learn the connectivity process. Before Starting make sure you have mongoDB installed in your computer system. These are some prerequisites that should be followed to get connected.

Prerequisites

  • A running MongoDB on localhost using the default port for MongoDB 27017. See Installation Mongodb installation steps.
  • MongoDB Driver.

After installing MongoDB, it is important to have mongodb driver as well. So to get these, you can either visit the official site MongoDB Java Driver or download the Jar file from our site. Keep this JAR file into your java application directory.

Note: We don’t need to use JDBC API for mongodb connectivity, It’s API is completely independent and does not require any other external library.

Following are the essential connectivity steps for Java application to mongodb database.

Create MongoDB Instance

You can instantiate a MongoClient object without any parameters to connect to a MongoDB instance running on localhost on port:27017. Use the following code.

MongoClient mongoClient = MongoClients.create();

You can specify the mongodb host and running port, in case mongodb is running on different port.

MongoClient mongoClient = MongoClients.create("mongodb://hostOne:27017");

Access a Database

After creating mongoDB instance, use its getDatabase() method to access a database by specifying the name of the database to the getDatabase() method. If a database does not exist, MongoDB creates the database when you first store data for that database. For example, we are connecting to studytonight database.

MongoDatabase database = mongoClient.getDatabase("studytonight");

Access a Collection

After creating mongoDB database, use its getCollection() method to access a collection by specifying name. If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

Use the following code to create collection, for example : student.

 MongoCollection<Document> collection = database.getCollection("student");

Create a Document

To create the document using the Java driver, use the Document class, and use its append() method to include additional fields and values to the document object. For example, see the following code.

Document doc = new Document("name", "Ramesh");
doc.append("id",12);

Insert a Document

After creating document, you can insert documents into the collection. We can insert single and multiple documents too. To insert a single document into the collection, you can use the collection’s insertOne() method.

	
collection.insertOne(doc);
	

To add multiple documents, you can use the collection’s insertMany() method which takes a list of documents to insert.

Fetch A Document

You can use the collection's find() method to fetch a record from the document. The find() method returns an iterable so you loop through to get individual data.

Now Lets put all these steps into one Java application and connect to the MongoDB database.

Java MongoDB Example:

Here we are connecting to mongodb by specifying the host and port number and then create a database and a collection to store the data. The insertOne() method is used to insert a single record to the document. See the below example.

	
import com.mongodb.MongoClient;  
import com.mongodb.client.MongoCollection;  
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
public class Demo {  
	public static void main(String[] args){  
		try{  
			// Connecting To MongoDB  
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );  
			// Creating DataBase   
			MongoDatabase db = mongoClient.getDatabase("studytonight");  
			// Creating Collection/Table  
			MongoCollection<Document> table = db.getCollection("student");  
			// Creating Document/Record    
			Document doc = new Document("name", "Ramesh");  
			doc.append("id",12);  
			// Inserting Data  
			table.insertOne(doc);  
		}catch(Exception e){  
			System.out.println(e);  
		}  
	}  
}  
	

Accessing Data from MongoDB

After creating database and inserting data, now lets fetch that record. We are using find() method to get records from the document and then iterating the record, and displaying by using their names. See the below example.

	
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;  
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
public class Demo {  
	public static void main(String[] args){  
		try{  
			// Connecting To MongoDB  
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );  
			// Creating DataBase   
			MongoDatabase db = mongoClient.getDatabase("studytonight");  
			// Creating Collection/Table  
			MongoCollection<Document> table = db.getCollection("student");  
			// Accessing Data
			FindIterable<Document> data =  table.find();
			// Traversing Data
			for(Document record : data) {
				System.out.println(record.getInteger("id")+" : "+record.getString("name"));
			}
			mongoClient.close();
			
		}catch(Exception e){  
			System.out.println(e);  
		}  
	}
} 
	

12 : Ramesh

Access in JSON Format

MongoDB is a document based database and used JSON like format to store the data into documents. It provides a method toJSON() to access data into JSON format that we used in this example.

	
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;  
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
public class Demo {  
	public static void main(String[] args){  
		try{  
			// Connecting To MongoDB  
			MongoClient mongoClient = new MongoClient( "localhost" , 27017 );  
			// Creating DataBase   
			MongoDatabase db = mongoClient.getDatabase("studytonight");  
			// Creating Collection/Table  
			MongoCollection<Document> table = db.getCollection("student");  
			// Accessing Data
			FindIterable<Document> data =  table.find();
			// Traversing Data
			for(Document record : data) {
				System.out.println(record.toJson());
			}
			mongoClient.close();
			
		}catch(Exception e){  
			System.out.println(e);  
		}  
	}
}
	

{"_id": {"$oid": "5ece65f5e8aa304abbf99953"}, "name": "Ramesh", "id": 12}