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

JDBCJava 8Object Oriented ProgrammingProgramming

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
raja
Published on 02-Apr-2019 16:46:39
Advertisements