How to connect MongoDB with Java or JDBC with MongoDB

How to connect MongoDB with Java or JDBC with MongoDB

Posted by Andy on 2015-03-28 07:11:14.0

Hi Andy,

If you want to connect MongoDB with Java or JDBC. First download eclipse-reporting-luna-SR2-win32-x86_64 or other higher version. 

Step 1. Go to ​Download Link. Download latest version of mongo-java-driver-2.13.1.jar or higher update. 
mongo java driver download

Step 2. Open eclipse, Right click on Project Explorer ⇒ New Project ⇒ Other ⇒ Java Project.

Step 3. Enter javaMongodnConnection in Project Name ⇒ Next ⇒ Finish

create a project

Step 4. Right Click on
javaMongodnConnection ⇒ New ⇒ Java Class and Enter Myconnection in Name ⇒ Finish. 
create class myConnection

Step 5. Now its time to add downloaded MongoDB Driver (mongo-java-driver-2.13.1.jar) in classpath.

Right Click to javaMongodnConnection Project ⇒ properties ⇒ Java Build Path ⇒ Add external Jars... Select the mongo-java-driver-2.13.1.jar file ⇒ OK. 
add jar to configuration build path

Step 6. Create Java class Myconnection . 
create connection

Step 7. insert data to your collection. 
insert statement

11. run MyCollection Class. On console you can see the output. 
output image

Thank You. 

Posted by Hitesh on 2015-05-10 07:52:14.0

Hi Andy ,

In order to connect MongoDB with java or JDBC you need to include mongo java driver in the build path of the project.

Solution : how to connect mongodb with java or JDBC

Step 1 : In your eclipse window , click on Project Properties


  • Click on Java Build Path ⇒ Add External Jars 
build path
  • Select the appropriate mongo java driver and click on OK.

Step 2 : Establish connection with MongoDB in the java class 
public class MongoConnection {

    public static void main(String[] args) {         
        Mongo mongo = null;
        DB db=null;
        DBCollection mongoCollection=null;
        // Connection to the MongoDB-Server
        try {
            mongo = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            System.out.println("error in connection");

Step 3 : Now you can query the database as you like . Following is an example to list all collections in a database named "demo" 
db = mongo.getDB("demo");
Set coll = db.getCollectionNames();         
for (String c : coll) {

Hope this helps.


Posted by Pathania on 2015-06-22 11:28:47.0