MongoDB Integration with Java

In this tutorial, we will discuss about how to integrate mongoDB with java client.

1. What is MongoDB ?

MongoDB is a very popular NoSql open source database. It works on collection rather than table and document rather than row and column that provides, high performance, high availability, and easy scalability.

Sample document :

1.1 What we’ll need

  • MongoDB 3.6
  • MongoDB-Java-Driver 2.10.1
  • JDK 1.8
  • Maven 3.0.3

1.2  Required dependencies

Now let’s start  implementation of mongo query with java, We  will start with CRUD operations.

2.Connection with MongoClient

If we use MongoDB version less than 2.10.0 then we use MongoDB server but we are using greater version so we will use MongoClient to make connection with mongoDB.

3. Connection with database

Now connect with database , if our database doesn’t exist than mongo will create new databse.

If we are using mongo in secure mode than authentication is required

Check which database is already exist with following code.

4. Mongo Collection

Now create collection which is equivalent to table in RDBMS. We can make collection as:

Get and print all existing collection for selected DB.

5. Insert Document

Now we will save a document (data) in collection (table).

Now One document has been inserted in database.

6. Update Document

Let’s assume we have following document

And we want to change First-Name of this document.

First search document where name=”Dharam” and update it with new values “Dharmendra”

7. Find  Document in Collection

Search a document where “firstName = Dharmendra” in user collection

8. Delete  Document

Delete a document where “firstName = Dharmendra” .

This tutorial was the quick introduction of mongodb with java.

Now find the complete code of mongoDB integration with java here.

Hope you liked the tutorial on how to integrate MongoDB with Java client. If you have any queries, feel free to contact us.

Leave a Reply