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="" xmlns:xsi="" xsi:schemaLocation="">

Step2: Java class looks like this



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();



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