How to connect MongoDB with Java ?

how to connect mongodb with java ?

How to connect MongoDB with Java ?: MongoDB is a document based open source data model. It stores the unstructured data’s in a JSON format. In our earlier posts we have seen how to install mongodb on windows 7 and resolved some of the most common issues while installing mongodb in windows 7.


How to install mongodb on windows 7 ?




mongo-java-driver (3.4.1 is the latest version when I am writing this post.)



Creating sample document named social in mongodb:


how to connect mongodb with java



Program Steps:


  1. Add the above downloaded mongo-java-driver to the buildpath.
  2. Connect to the localhost mongodb with the port 27017(mongodb default port) using MongoClient.
  3. Access the document/collection of mongodb using getCollection() method.
  4. Find() method returns MongoIterable iterator and using MongoCursor values can be checked and read using hasNext() and next() method respectively.



Connecting MongoDB with Java Sample Program:


package in.javadomain;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoIterable;

public class ConnectMongoDB {
public static void main(String[] args) {
// 27017 is the default port value of mongodb
MongoClient client = new MongoClient("localhost", 27017);

// To print the total collections count

// To print all the values from the social collection/document
MongoCollection mCollections = client.getDatabase("my_mongo")
MongoIterable mIterable = mCollections.find();
MongoCursor mCursor = mIterable.iterator();
while (mCursor.hasNext()) {






Console Output:


Document{{_id=585acaac7af88224474d0f06, name=Facebook,}}
Document{{_id=585acab37af88224474d0f07, name=Twitter,}}
Document{{_id=585acabc7af88224474d0f08, name=GPlus,}}
Document{{_id=585acac27af88224474d0f09, name=Pinterest,}}






 1,536 total views,  9 views today

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.