How to Set up MongoDB JDBC driver

Last updated on May 30 2022
Satyen Sahu

Table of Contents

How to Set up MongoDB JDBC driver

MongoDB – Java

In this blog, we will learn how to set up MongoDB JDBC driver.
Installation
Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB JDBC driver.
• You need to download the jar from the path Download mongo.jar. Make sure to download the latest release of it.
• You need to include the mongo.jar into your classpath.

Connect to Database

To connect database, you need to specify the database name, if the database doesn’t exist then MongoDB creates it automatically.
Following is the code snippet to connect to the database −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class ConnectToDB {

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”);
System.out.println(“Credentials ::”+ credential);
}
}
Now, let’s compile and run the above program to create our database myDb as shown below.
$javac ConnectToDB.java
$java ConnectToDB
On executing, the above program gives you the following output.
Connected to the database successfully
Credentials ::MongoCredential{
mechanism = null,
userName = ‘sampleUser’,
source = ‘myDb’,
password = <hidden>,
mechanismProperties = {}
}

Create a Collection

To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.
Following is the code snippet to create a collection −
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”);
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully

Getting/Selecting a Collection

To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used.
Following is the program to get/select a collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class selectingCollection {

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”);

// Retieving a collection
MongoCollection<Document> collection = database.getCollection(“myCollection”);
System.out.println(“Collection myCollection selected successfully”);
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully
Collection myCollection selected successfully

Insert a Document

To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used.
Following is the code snippet to insert a document −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class InsertingDocument {

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”);

// Retrieving a collection
MongoCollection<Document> collection = database.getCollection(“sampleCollection”);
System.out.println(“Collection sampleCollection selected successfully”);

Document document = new Document(“title”, “MongoDB”)
.append(“id”, 1)
.append(“description”, “database”)
.append(“likes”, 100)
.append(“url”, “http://www.tecklearn.com/mongodb/”)
.append(“by”, “tecklearn”);
collection.insertOne(document);
System.out.println(“Document inserted successfully”);
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Document inserted successfully

Retrieve All Documents

To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor.
Following is the program to select all documents −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class RetrievingAllDocuments {

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”);

// Retrieving a collection
MongoCollection<Document> collection = database.getCollection(“sampleCollection”);
System.out.println(“Collection sampleCollection selected successfully”);

// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;

// Getting the iterator
Iterator it = iterDoc.iterator();

while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Document{{
_id = 5967745223993a32646baab8,
title = MongoDB,
id = 1,
description = database,
likes = 100,
url = http://www.tecklearn.com/mongodb/, by = tecklearn
}}
Document{{
_id = 7452239959673a32646baab8,
title = RethinkDB,
id = 2,
description = database,
likes = 200,
url = http://www.tecklearn.com/rethinkdb/, by = tecklearn
}}

Update Document

To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used.
Following is the program to select the first document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class UpdatingDocuments {

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”);

// Retrieving a collection
MongoCollection<Document> collection = database.getCollection(“sampleCollection”);
System.out.println(“Collection myCollection selected successfully”);

collection.updateOne(Filters.eq(“id”, 1), Updates.set(“likes”, 150));
System.out.println(“Document update successfully…”);

// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;

// Getting the iterator
Iterator it = iterDoc.iterator();

while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Document update successfully…
Document {{
_id = 5967745223993a32646baab8,
title = MongoDB,
id = 1,
description = database,
likes = 150,
url = http://www.tecklearn.com/mongodb/, by = tecklearn
}}

Delete a Document

To delete a document from the collection, you need to use the deleteOne() method of the com.mongodb.client.MongoCollection class.
Following is the program to delete a document −
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class DeletingDocuments {

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”);

// Retrieving a collection
MongoCollection<Document> collection = database.getCollection(“sampleCollection”);
System.out.println(“Collection sampleCollection selected successfully”);

// Deleting the documents
collection.deleteOne(Filters.eq(“id”, 1));
System.out.println(“Document deleted successfully…”);

// Retrieving the documents after updation
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;

// Getting the iterator
Iterator it = iterDoc.iterator();

while (it.hasNext()) {
System.out.println(“Inserted Document: “+i);
System.out.println(it.next());
i++;
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Document deleted successfully…

Dropping a Collection

To drop a collection from a database, you need to use the drop() method of the com.mongodb.client.MongoCollection class.
Following is the program to delete a collection −
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class DropingCollection {

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(“Collections created successfully”);

// Retieving a collection
MongoCollection<Document> collection = database.getCollection(“sampleCollection”);

// Dropping a Collection
collection.drop();
System.out.println(“Collection dropped successfully”);
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection sampleCollection selected successfully
Collection dropped successfully

Listing All the Collections

To list all the collections in a database, you need to use the listCollectionNames() method of the com.mongodb.client.MongoDatabase class.
Following is the program to list all the collections of a database −
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class ListOfCollection {

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”);
System.out.println(“Collection created successfully”);
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully
myCollection
myCollection1
myCollection5
So, this brings us to the end of blog. This Tecklearn ‘How to Set up MongoDB JDBC driver’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "How to Set up MongoDB JDBC driver"

Leave a Message

Your email address will not be published. Required fields are marked *