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?
- 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.
- It allows us to index any field in the document to improve search results.
- 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.
- 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
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.10.2</version> </dependency> </dependencies>
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"); getCollection().insertOne(document);
Reading the data from Collection
We can get the document from collection using the find() method.
Document document = getCollection().find().first(); System.out.println(document.toJson());
Updating the data
We can update the Document using updateOne() method which will update one document.
getCollection().updateOne( eq("firstName", "Upanshu"), combine(set("age", "23"), set("lastName", "Singh"))); System.out.println("successful");
Delete a Document
To delete a Document we can use deleteMany() method.
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.