How to connect to a MongoDB database using a JDBC program?


MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Before you start connecting MongoDB in you need to make sure that you have MongoDB JDBC driver. If not, download the jar from the path Download mongo.jar and, add it to your classpath.

Example

Following JDBC program establishes connection with the MongoDB database and creates a collection in it.

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      // Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
      System.out.println("Connected to the database successfully");
      //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");
      //Creating a collection
      database.createCollection("sampleCollection");
      System.out.println("Collection created successfully");
   }
}

Output

Connected to the database successfully
Collection created successfully

Updated on: 30-Jul-2019

993 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements