How to connect MongoDB using Java

How to connect MongoDB using Java


Here are the steps to connect the MongoDB from the java class.

Obviously this is not all you are looking for, this will provide you a basic idea of connecting a mongo DB using java. The easiest DB connection so far I have seen is this. All you need to do is download the driver class or include it in your pom dependency and create a main class with two method calls.

You are ready to go !!!

Step 1: Download / Add your pom dependency.

pom.xml looks like this


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.apc</groupId>
 <artifactId>m101j</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <dependencies>
 <dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>2.10.1</version>
 </dependency>
 </dependencies>
</project>

Step2: Java class looks like this


package com.abc.mongo;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class Main {

/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException {

MongoClient client = new MongoClient( new ServerAddress(&quot;localhost&quot;, 27017));

DB db = client.getDB(&quot;DBNAME&quot;); \\ Usally there is always a DB with name test

DBCollection collection = db.getCollection(&quot;COLLECTIONNAME&quot;); \\ You can easily create a collection by going to Mongo Shell.

DBObject document = collection.findOne();

System.out.println(document);
}

}

Try to run this main program and you would be able to see the output of the Collection results on the console.

Hope this was helpful. Thanks

Other Useful references :

MongoDB Commands Help

MongoDB University Where you can attend MooC

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s