1 Answer
Vrundesha Joshi

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.


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
      System.out.println("Collection created successfully");


Connected to the database successfully
Collection created successfully


We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.