MongoDB Connection in Java

If you are looking for the right guide to learn MongoDB connection Java, you are at the right stop. This blog explores the MongoDB connection in Java through various methods with simple step-by-step procedures. Go through the blog entirely to gain solid hands-on skills on Mongodb connection in Java. In this blog, you will learn how to connect to the Mongodb database with Java driver, JNDI Datasource, etc.

Before diving deep into the MongoDB connection in Java, let’s take a glance at what the MongoDB database is. Mongodb is nothing but a document-based NoSQL open-source database. MongoDB is written in C++ language. It has key features like map-reduce, horizontal scalability, high availability, replication, etc.

MongoDB stores data in JSON files so that you can store data in various formats. This database uses dynamic schemas so you can create records quickly. You can only connect with the MongoDB database using the MongoDB Java driver API. You cannot use the JDBC-complaint drivers that you commonly use to communicate with relational databases.

In this blog, we will learn MongoDB connection in Java using the Java driver. Also, you will learn to make CRUD operations in MongoDB, connect to MongoDB with JNDI Datasource, and a lot more in this blog.

Let’s get started!

Table of Contents

Prerequisites

  • Installation of MongoDB on your machine. You can use the below link to download the MongoDB community server.
  • Download the MongoDB Java driver. You can use the below link to download the MongoDB Java driver. Note that the file type is a jar.

Once you satisfy the prerequisites, it’s time to start your journey to learn how to connect to MongoDB in Java.

If you want to enrich your career and become a professional in MongoDB, then visit MindMajix - a global online training platform: "MongoDB Certification Training" This course will help you to achieve excellence in this domain.

MongoDB Connection using the Java Driver

This quick guide will help you how to connect to a MongoDB instance using a Java driver. Mongoclient and connection URIs play key roles in the MongoDB connection in Java.

  • Connecting to MongoDB using Mongoclient:

You can use the Mongo client class to connect and interact with MongoDB. So you can make various database operations in the MongoDB database. You need to use the Mongo client. create a ( ) method to create a Mongo client.

1. You can use the following command to connect to a MongoDB server

MongoClient mongoClient=MongoClients.create("mongodb://localhost:27017");

2. If you want to create a Mongo client instance, then you can use the below code to connect to a default MongoDB server that runs on the default port and local host.

MongoClient mongoClient = new MongoClient();

3. If you want to connect to a named MongoDB server that listens on the default port, then you can use the below code.

MongoClient mongoClient = new MongoClient("localhost");

4. If you want to connect to a name MongoDB server that listens to a specific port, then you can use the below code.

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

5. If you want to connect to a replica set of servers, you can use the below code.

List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(new ServerAddress("db1.server.com", 27017));
seeds.add(new ServerAddress("db2.server.com", 27018));
seeds.add(new ServerAddress("db3.server.com", 27019));
MongoClient mongoClient = new MongoClient(seeds);

6. Once the connection is set, you can access the MongoDB database and make authentication. You can use the below code for the same.

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB ("test");
char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
boolean authenticated = db.authenticate("root", password);
if (authenticated) {
System.out.println("Successfully logged in to MongoDB!");
} else {
System.out.println("Invalid username/password");
}
  • Showing existing MongoDB databases

1. You can use the below command to display databases in Java.

MongoClient.listDatabasesNames().forEach (System.out::println);

2. You will get the output as shown below:

local     0.000GB
myMongoDb 0.000GB

Here, local is nothing but the default Mongo database.

  • Connecting to MongoDB using the connection URI

Know that the Java Driver uses the connection URI to connect with MongoDB. Connection URI is nothing but a set of instructions. It directs the Java driver to connect to MongoDB. You can find the standard format of the connection URI below. This connection URI is framed based on the standard connection string format. Additionally, you can also use the DNS seed list connection list format. This later format provides more flexibility. Also, it allows changing servers in rotation without reconfiguring clients.

Let’s go through the different parts of the connection URI in the following.

The connection URI has a credential part that has sections of user and pass. The user represents the username, and the pass represents your password. Following that, you can find the hostname and IP address in the URI. This part also includes the MongoDB port address. The connection options are the last part of the connection URI.

MindMajix Youtube Channel

  • Connecting to a MongoDB deployment on a local machine:

If you want a MongoDB deployment on a local machine, you need to follow the below steps.

  1. First, you need to download, install, and configure the community or enterprise version of the MongoDB server
  2. Initiate the deployment
  3. Specify your connection string in the driver connection code
  4. You can use the below connection string if your MongoDB deployment runs locally.

“mongodb://localhost:<port>”       

Now, you have learned how to connect to MongoDB using the Java driver in various ways. Next, we will see how to make multiple operations in MongoDB once the connection is established.

Making CRUD operations in MongoDB

In this quick guide, we will go through the CRUD operations that we can make with MongoDB after making the connection with the MongoDB database.

  • Creating collections:

A collection is nothing but a table equivalent in MongoDB. After connecting with the MongoDB database, you can start creating collections.

Below is the step-by-step procedure to create collections.

1. You can use the following command to create a collection in the database

database.createCollection ("customers");

2. You can use the below command to display all the existing collections of the MongoDB database

database.listCollection Names().forEach (System.out::println);

3. Now, you will get the output as shown below:

‘customers’

  • Saving data in MongoDB database with insert semantics

You can save data in MongoDB databases using the save operation. For example, you can save the details of a new customer.

1. You can use the below code to save a new customer

MongoCollection <Document> collection = database.getCollection ("customers");
Document document = new Document();
document.put("name", "David");
document.put("company", "MM");
collection.insertOne (document);

2. After the execution, you will get the result as follows:

{
"_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
"name" : "David",
"
'company" : "MM"
}
  • Saving data in the MongoDB database with updated semantics

You can update the existing customer data using save-update semantics.

1. consider below the existing customer record

{
Sung
"_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
"name" : "David",
"company": "MM"
}

2. You can update the record using the following commands

Document query = new Document();
query.put("name", "David");
Document newDocument = new Document();
newDocument.put("name", "Joseph");
Document updateObject = new Document();
updateObject.put("$set", newDocument);
collection.updateOne (query, updateObject);

3. You will get the output of the database as follows:

{
"_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
"name": "Joseph",
"company" : "MM"
}
  • Searching for a document from a collection

You can read a document from a collection of the mongoDB database in the following way.

1. You can make a MongoDB query using the below commands

Document searchQuery = new Document();
searchQuery.put("name", "Joseph");
FindIterable<Document> cursor = collection.find(searchQuery);
try (final MongoCursor <Document> cursorIterator = cursor.cursor()) {
while (cursorIterator.hasNext()) {
         System.out.println(cursorIterator.next());
    }
}

You will get the output from the database as below.

[
    {
        "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
        "name": "Joseph",
        "company": "MM"
        }
  ]
  • Deleting a document from the database

You can delete data from MongoDB using the command.

Document searchQuery = new Document();
searchQuery.put("name", "Joseph");
collection.deleteOne (searchQuery);

Right now, you have gained solid hands-on experience in how to make CRUD operations in MongoDB database.

Connecting to MongoDB using JNDI Datasource

         In this quick guide, you will get to know how to connect a MongoDB instance using JNDI Datasource. JNDI is nothing but Java Naming and Directory Interface.

  • First, Install Apache Tomcat on your machine. You can use the below link to download the latest version of Apache Tomcat.
  • Copy the mongo-java-driver.jar file into the Apache Tomcat'slib directory.
  • Next, add a resource that references the mongoclientfactory class in the context.xml file of your application. The resource should also refer to the connection string for the MongoDB cluster.
<Resource name="mongodb/MyMongoClient"
auth="Container"
type="com.mongodb.MongoClient"
closeMethod="close"
factory="com.mongodb.client.MongoClientFactory"
singleton="true"
connectionString="<connection string uri>"/>
  • Add a reference to the mongoclientfactory resource in the web.xml of your application.
<resource-ref>
<res-ref-name>
mongodb/MyMongoClient
</res-ref-name>
<res-type>
com.mongodb. MongoClient
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
  •  Now, you can identify a mongoclient instance through the JDNI name mongodb/MyMongoClient in the Java: comp/env context.

Well! You have learned how to connect to MongoDB using JNDI Datasource. Let’s look into how to connect with MongoDB using the JDBC connector.

Connecting to MongoDB using the JDBC Connector

JDBC stands for Java DataBase Connectivity. In a way, it is a Java API used to execute database queries. With JDBC, you can access data from relational databases. When it comes to the MongoDB database, we can use JDBC to make updates in the database and call stored procedures. We can use JDBC to connect Java applications with databases. This connector uses SSL protocol to make secure database connections.

Now, you will go through the procedure to use JDBC to connect with MongoDB databases.

  • Adding the JDBC driver JAR files
  1. First, you must add the JDBC driver to the built path. To do so, click on the package explorer section and hit Alt+Enter. Then click on the Java build path.
  2. Next, click the ‘add external JARs’ button and find the recently downloaded JDBC Driver JAR files.
  3. You can choose the unityjdbc.jar along with mongo-java-driver-2.12.2.jar.
  • Importing Java. SQL package:

Let’s import the java.sql.* classes to make a connection with MongoDB. You can use Java class import statements for the same. You can find the statements below:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
  • Registering the database driver

Know that it is crucial to register the driver for the MongoDB JDBC connection. You can use the class.forname method to complete the registration.

try {
Class.forName("mongodb.jdbc.MongoDriver");
} catch (ClassNotFoundException e) {
System.out.println("ERROR: Unable to load SQLServer JDBC Driver");
e.printStackTrace();
return;
}
  • Creating the database connection

Now, you can use the DriverManager.getConnection method shown below. This method helps to establish the connection with the MongoDB database.

  • Creating the JDBC statement

Once the MongoDB JDBC connection is established, you can use the JDBC createstatement (),preparestatement (), and preparecall (),  methods to send and receive data in the MongoDB database. You can use the below code for the same.

  • Resultset

The resultset contains the data returned because of a database query. Resultset is maintained in the Javadocs. The following helps to understand it better.

try{
statement = connection.createStatement();
result = statement.executeQuery("select employee_id, first_name, last_name from employe
while (result.next()) {
String employee_id = result.getString("employee_id");
String first_name = result.getString("first_name");
String last_name = result.getString("last_name");
System. out.printf("Employee ID: [%s], %s %s n", employee_id, first_name, last_name);
}
}   catch (SQLException e) {
     System.out.println(e.getMessage());
}
  • Closing the connection

Lastly, you need to close the database connections along with the resources.

} finally {
if (connection != null) connection.close();
}

Congrats! You have gained hands-on experience in connecting with the MongoDB database through various methods.

FAQs

1. What is MongoDB?

MongoDB is a document database that offers high scalability and flexibility. You can access the MongoDB in the cloud and on-premises.  The great thing about MongoDB is that it is a go-to tool for developers as it resolves the complex requirements of developers quickly.

2. What are the key features of MongoDB?

  •  It provides high availability
  •  It offers horizontal scalability
  •  It provides improved security.

3. What is the difference between SQL and MongoDB databases?

We use SQL databases to store structured data. On the other hand, we use the MongoDB database to store unstructured data. The unstructured data is stored in JSON format.

4. Which query language does mongoDB support?

MongoDB supports MongoDB query language (MQL). On the other hand, relational databases support SQL language.

5. Does MongoDB work faster than MySQL?

MongoDB usually stores related data together so that you can retrieve a single document from mongoDB faster than MySQL.       

Conclusion

It’s time to wrap! You have gone through various procedures for MongoDB connection in Java. In summary, you have learned how to make MongoDB connections with Java drivers, make CRUD operations in MongoDB, connect with MongoDB using JNDI Datasource, and connect with MongoDB using the JDBC connector.

We hope that the hands-on skills that you have gained through this blog will help you in the real-time work environment. If you want to explore more about MongoDB, you can sign up for the Mongodb training with MindMajix and get certification. It will help you to advance your career undeniably.

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
MongoDB Training Dec 07 to Dec 22View Details
MongoDB Training Dec 10 to Dec 25View Details
MongoDB Training Dec 14 to Dec 29View Details
MongoDB Training Dec 17 to Jan 01View Details
Last updated: 23 Feb 2024
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read less