Introduction to MongoDB with Java

Reading Time: 3 minutes

We now live in a data driven world where we are generating so much data that it becomes difficult to manage this data using databases. There are different databases available for different use cases. For a long time Relational databases were used for most of the uses cases, but as the technology advanced and modern applications came which need more scalability and variety came into picture it became important to choose the right database. This is where one of the No-SQL databases comes in such as MongoDB. In this blog we will have an Introduction to MongoDB and how we can get started with MongoDB with java.

What is MongoDB?

MongoDB is an open-source non relational, document oriented database. MongoDB being document oriented means that it stores data in JSON like documents which makes it more powerful and expressive. Data is stored in documents in Key pair values.

Another component of MongoDB is collection which is the collection of documents. Collection corresponds to Table in relational databases.

Figure: MongoDB Document

Why use MongoDB?

  1. It is document based and therefore it is more flexible where each document can have varying fields which can not be done in relational databases.
  2. It allows us to index any field in the document to improve search results.
  3. It provides us with rich and powerful query language which allows us to filter and sort using any field no matter how nested the field is.
  4. It provides us with High scalability(sharding ) and high availability(replication) of data.

Using MongoDB with Java

Till now we have a basic understanding of MongoDB and why we should use Mongo as our preferred database. Now we will look at how we can interact with Mongo using Java by making a small CRUD application. 

To run this application you need a Mongo environment installed on your local machine. You can do that by following the steps given here.

Once you are done with that let’s start building our CRUD application.

The first thing we need to do to use Mongo with java is to add the MongoDB dependency in our pom.xml








Connecting to Database

Assuming that we are done with project setup and have resolved dependency now we will connect to Mongo using java. 

To interact with MongoDB you need to establish an initial connection with it. For that we will create a MongoClient. It is the interface between your java program and Mongo server. MongoClient can be used to establish connections, connect to databases and perform crud operations on databases.

String uri = "mongodb://localhost:27017";

MongoClientURI mongoClientURI = new MongoClientURI(uri);

MongoClient mongoClient = new MongoClient(mongoClientURI);

Here the uri is the localhost:2701 which is the default port for MongoDB instances. You can change this uri if this Mongo instance runs on a different port.

Creating a Collection

Once we are done with establishing the connection now we can create a database. We can create a database by calling the getDatabase() with our MongoClient.

MongoDatabase mongoDatabase = mongoClient.getDatabase("CrudDB");

If the database does not exist this will create a new database with name “CrudDB”

To retrieve documents from this database we can use the getCollection() method using the MongoClient.

MongoCollection<Document> collection = mongoDatabase.getCollection("testOne");

Creating a New Document

To Create a new document and insert values to it we will use the insertOne() method which will insert one document in the collection. You can also use the insertMany().

Method which will insert a list of multiple documents in the collection.

Document document = new Document()

    .append("firstName", "Upanshu")

    .append("lastName", "Chaudhary")

    .append("age", "22")

    .append("gender", "Male")

    .append("designation", "Software Consultant");


Reading the data from Collection

We can get the document from collection using the find() method.

Document document = getCollection().find().first();


Updating the data

We can update the Document using updateOne() method which will update one document.


eq("firstName", "Upanshu"),

combine(set("age", "23"), set("lastName", "Singh")));


Delete a Document

To delete a Document we can use deleteMany() method.

getCollection().deleteMany(eq("age", "22"));

These are the basic CRUD Operations you can perform on MongoDB using java. You can define the project structure yourself and create functions for each operation.

GitHub link for the application can be found here

Learn all you can about Mongo from the knoldus Blogs here.



This image has an empty alt attribute; its file name is footer-2.jpg

Leave a Reply