Our world is now data-driven, where big corporations are generating data at a very rapid pace. With trillions of data points to capture, companies are now looking for technology that can enable them not only to store the big data but also able to access or process them seamlessly.

If you are not new to the database, then you should know how reliable it is a relational database. Most companies rely heavily on it for data storage and operations purposes. However, there is always a limitation with relational databases. Right now, the industries demand more flexibility and scalability that can work with big data. This is where the concept of No-SQL databases comes in.

In this article, we will look at one of the modern database solutions, MongoDB – a No-SQL database that provides a different way to handle data. To showcase what MongoDB is capable of we are going to use the Java programming language as well. Java is a well-known programming language with enterprise development. It is a modern object-oriented programming language.

 

Getting Started With MongoDB

What is MongoDB?

MongoDB describes itself as the database for modern applications. Technically, it is a NoSQL database that offers a document-based, general-purpose distributed database. It is built for the cloud era and is ideal for modern application developers. The non-relational approach makes its approach different. Here, the data is stored and accessed via key-value pairs. It is also open source which means you will get a lot of support for development queries and problems.

MongoDB offers multiple key features including auto-scaling which ensures that it is made for enterprise. MongoDB is also cross-platform ready which means that you can work on different platforms as a developer.

Below is an example showing the MongoDB document structure.

{
"_id": "11222dsadsdt5242",
"firstname": "Nitish",
"lastname": "Sin",
"address": {
"street": "Chingchang ",
"city": "Los Santosh",
"state": "CA",
"zip": "23232"
},
"hobbies": ["racing", "coding"]
}

MongoDB History

Technologies evolve over time, and that’s why it is important to know about their history. MongoDB history started in 2007 when Eliot Horowitz and Dwight Merriman struggled with relational database scalability issues during enterprise development. And, that’s why they created MongoDB. The word choice from the fact that the word means humongous, which means support for large processing data.

By 2009, the project was made open source, which meant that many organizations and developers work towards its improvement by adding new features. In 2014, the company that managed the technology is named MongoDB Inc.

 

Why use MongoDB?

Before we get started with MongoDB with Java, let’s learn the reasons why use MongoDB.

  • The document-based approach means that it offers flexibility when developing applications. For instance, the documents can have varying fields, which is not possible in relational databases.
  • You get access to a powerful query language that lets you sort and filter fields.
  • Indexing of results ensures faster performance.
  • It offers high availability and scalability.

 

MongoDB and Java

Now that we have a clear understanding of MongoDB, it is now time to look at it in action. For this purpose, we are going to use the Java Programming language. To showcase the MongoDB capabilities, we are going to make a simple application using Java and MongoDB and run CRUD functionality on them.

For that purpose, you need to have a proper MongoDB environment installed on your local machine. For this purpose, we are going to install it on Windows 10 environment. You can easily adapt the installation process depending on your operating system.

To get started, you need to visit their MongoDB community edition page. For this tutorial, we are going to use the MongoDB 4.4 version.

 

Click on the Download button to start your download. From here, you need to install MongoDB with the help of the wizard. It’s easy and you surely won’t feel stuck with it. In our experience of installation, it can take quite a while depending on your internet, SSD, and more!

Let’s get started with our CRUD application.

To get started, we first need to create MongoDB dependency with our Java application. To do so, we need to edit the pom.xml file.

 

<dependencies>

<dependency>

<groupId>org.mongodb</groupId>

<artifactId>mongo-java-driver</artifactId>

<version>3.10.2</version>

</dependency>

</dependencies>

 

MongoDB Connection And CRUD Operations

With our Java dependency sorted out, it is now time for us to connect Java with the MongoDB database. To do so, our first step would be to rate a MongoClient which ensures that the initial connection is established. The MongoClient takes care of the interface between the Mongo server and the java program. There are other features that are supported by MongoClient interface including the ability to make CRUD operations, establish connections to databases, and so on!

Connecting With Database

So, what code you needed to create the MongoClient? Well, you can use the code as shown below.

String uri = “mongodb://localhost:27017”;

MongoClientURI mongoClientURI = new MongoClientURI(uri);

MongoClient mongoClient = new MongoClient(mongoClientURI);

Port Selection

As you can see, we have used localhost:2701.

2701 is the default port for MongoDB. In case the port is not free, you can decide to change it based on your requirement. In most cases, there won’t be an issue.

Terminologies

Before we proceed further, it is important to understand the terminologies for MongoDB.

  • Collection: It is equivalent to Table in MySQL.
  • Document: It is equivalent to Row in MySQL
  • Field: It is equivalent to Column in MySQL.
  • Linking: It is equivalent to embedded and linking documents.

If you have used a MySQL based database earlier, this should make sense to you.

Show Databases

You can easily showcase the existing databases. To showcase the databases listed within MongoDB, you need to run the following command.

show databases;

In case you want to showcase the database using Java, then you need to use the following command.

mongoClient.getDatabaseNames().forEach(System.out::println);

As we have created one database until now(during a connection, it automatically creates a database), you should get an output showing two databases as below.

 

local 0.000GB

myMongoDb 0.000GB

The local database is designated as the default Mongo database.

 

Creating Collection

As we are now connected to the database, we will now ready to create our first collection.

To create the collection, you need to use the following command.

database.createCollection(“readers”, null);

 

To showcase the collection within the database, you need to use the following:

database.getCollecitonNames().forEach(System.out::println);

 

The output for the above command will be as follows:

readers

 

Insert New Data

It is now time to insert new data. We are going to use the save operation. So, if you have an id present, then the save operation will do an update. In case there is no id, then the save operation will do an insert. Sounds good!

 

DBCollection collection = database.getCollection(“readers”);

BasicDBObject document = new BasicDBObject();

document.put(“name”,”Nitish”);

document.put(“company”,”Freelancer”);

collection.insert(document);

 

The database entity will now be updated as below.

{
"_id" : ObjectId("234242ef232dsa23232fsadas"),
"name" : "Nitish",
"company" : "Freelancer"
}

Update new data

With the collection created, now it is time to update it.

{
"_id" : ObjectId("234242ef232dsa23232fsadas"),
"name" : "Nitish",
"company" : "Freelancer"
}

Now, let’s use the save operation to update it.

 

BasicDBObject query = new BasicDBObject();

query.put(“name”, “Nitish”);

 

BasicDBObject newDocument = new BasicDBObject();

newDocument.put(“name”,”Markel”)

 

BasicDBObject updateObject = new BasicDBObject();

updateObject.put(“$set”, newDocument);

 

collection.update(query, updateObject);

 

After you run all the queries as mentioned above, the collection will be updated as below.

{
"_id" : ObjectId("234242ef232dsa23232fsadas"),
"name" : "Markel",
"company" : "Freelancer"
}

 

Reading the document

To read the document, you need to use the following set of commands.

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put(“name”, “Markel”);
DBCursor cursor = collection.find(searchQuery);

while (cursor.hasNext()) {
System.out.println(cursor.next());
}

It will return the following.

[
{
"_id" : ObjectId("234242ef232dsa23232fsadas"),
"name" : "Markel",
"company" : "Freelancer"
}
]

 

Deleting document

The final query that we are going to look at is to delete the document.

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put(“name”, “Markel”);

collection.remove(searchQuery);

 

Final Thoughts

This leads us to the end of our Introduction to MongoDB with Java. We hope you now have a clear understanding of what’s at the offer. In case if you want to learn more, then check out the official documentation to know more!