i

Java Connector

MongoDB provides connectivity for Java client applications using Java driver. Using the Java driver is simple, just include the driver jar mongo.jar in your classpath. The below java code chunk will help us to connect to mongodb.

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

import com.mongodb.MongoClient;

import java.util.List;

import java.util.Set;

import static java.util.concurrent.TimeUnit.SECONDS;

 

public class mongodb_connection{

   public static void main( String args[] ){

      try{  

                                MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

                                System.out.println("Database Connection Successful!");

        DB db = mongoClient.getDB( "library" );

                    }catch(Exception e){

                     System.err.println( e.getClass().getName() + ": " + e.getMessage() );

                  }

   }

}

Output:

Database Connection Successful!