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.
Table of Contents
Requirements:
mongo-java-driver (3.4.1 is the latest version when I am writing this post.)
Creating sample document named social in mongodb:
Program Steps:
- Add the above downloaded mongo-java-driver to the buildpath.
- Connect to the localhost mongodb with the port 27017(mongodb default port) using MongoClient.
- Access the document/collection of mongodb using getCollection() method.
- 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:
[java]
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();
}
}
[/java]
Console Output:
[plain]
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}}
[/plain]