How to connect MongoDB with Java ?

how to connect mongodb with java ? (Last Updated On: December 22, 2016)

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 ?

 

 

Requirements:

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
System.out.println(client.getDatabase("my_mongo")
.getCollection("social").count());

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

client.close();

}
}

 

 

 

Console Output:


4
Document{{_id=585acaac7af88224474d0f06, name=Facebook,url=www.facebook.com}}
Document{{_id=585acab37af88224474d0f07, name=Twitter, url=www.twitter.com}}
Document{{_id=585acabc7af88224474d0f08, name=GPlus, url=www.plus.google.com}}
Document{{_id=585acac27af88224474d0f09, name=Pinterest, url=www.pinterest.com}}

 

 

 

 

308 total views, 2 views today

Leave a Reply

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