{{announcement.body}}
{{announcement.title}}

MongoDB Integration With Java

DZone 's Guide to

MongoDB Integration With Java

This tutorial explains how to integrate MongoDB with Java client.

· Database Zone ·
Free Resource

In this tutorial, we will discuss 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 :

{

   "_id" : ObjectId("5b0d226b31a5f6595a7034de"),

   "firstName" : "Dharam",

   "lastName" : "Rajput"

}


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

<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
 </dependencies>


Now let’s start the implementation of Mongo query with Java, We will start with CRUD operations.

2. Connection With MongoClient

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

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

// If we use older version than

Mongo mongo = new Mongo("localhost", 27017);


3. Connection With the Database

Now connect with the database. If your database doesn’t exist, then Mongo will create a new database.

DB database = mongoClient.getDB("testdb");


If we are using Mongo in a secure mode, then authentication is required.

MongoClient mongoClient = new MongoClient();
DB database = mongoClient.getDB("testdb"); // testdb is db name
boolean auth = database.authenticate("username", "password".toCharArray());


Check which database already exists with the following code.

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


4. Mongo Collection

Now, create a collection that is equivalent to table in RDBMS. We can make the collection as:

database.createCollection("users", null);


Get and print all existing collections for selected DB.

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


5. Insert Document

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

DBCollection table = db.getCollection("users");
BasicDBObject document = new BasicDBObject();
document.put("firstName", "Dharam");
document.put("lastName", "Rajput");

table.insert(document);


Now one document has been inserted in the database.

{

   "_id" : ObjectId("5b0d226b31a5f6595a7034de"),

   "firstName" : "Dharam",

   "lastName" : "Rajput"

}


6. Update Document

Let’s assume we have the following document:

{

   "_id" : ObjectId("5b0d226b31a5f6595a7034de"),

   "firstName" : "Dharam",

   "lastName" : "Rajput"

}


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

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

BasicDBObject query = new BasicDBObject();
query.put("firstName", "Dharam");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("firstName", "Dharmendra");
BasicDBObject updateObj = new BasicDBObject();

updateObj.put("$set", newDocument);


7. Find the Document in Collection

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

DBCollection db= db.getCollection("user");

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("firstName", "Dharmendra");
DBCursor cursor = db.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}


8. Delete Document

Delete a document where “firstName = Dharmendra” .

DBCollection db= db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
db.remove(searchQuery);


This tutorial was the quick introduction of MongoDB with Java.

Now find the complete code of MongoDB integration with Java here.

package com.demo.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

public class TestDB {

public static void main(String[] args) {

try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongoClient = new MongoClient("localhost", 27017);

/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you

DB db = mongoClient.getDB("testdb");
mongoClient.getDatabaseNames().forEach(System.out::println);

/**** Get collection / table from 'testdb' ****/

// if collection doesn't exists, MongoDB will create it for you

DBCollection collection = db.getCollection("users");

/**** Insert ****/

// create a document to store key and value

BasicDBObject document = new BasicDBObject();

document.put("firstName", "Dharam");

document.put("lastName", "Rajput");

collection.insert(document);

/**** Find and display ****/

BasicDBObject searchQuery = new BasicDBObject();

searchQuery.put("firstName", "Dharam");

DBCursor dbCursor = collection.find(searchQuery);
while (dbCursor.hasNext()) {

System.out.println(dbCursor.next());

}

/**** Update ****/

// search document where name="Dharam" and update it with new values "Dharmendra"

BasicDBObject dbQuery = new BasicDBObject();

dbQuery.put("firstName", "Dharam");

BasicDBObject newDocument = new BasicDBObject();

newDocument.put("firstName", "Dharmendra");

BasicDBObject updateObj = new BasicDBObject();

updateObj.put("$set", newDocument);

collection.update(dbQuery, updateObj);

/**** Find and display ****/

BasicDBObject findQuery

&nbsp;&nbsp;&nbsp;= new BasicDBObject().append("firstName", "Dharmendra");

DBCursor findCursor = collection.find(findQuery);

while (findCursor.hasNext()) {

System.out.println(findCursor.next());

}

&nbsp;&nbsp;&nbsp;} catch (Exception e) {

e.printStackTrace();

&nbsp;}

}

}


I hope you liked the tutorial on how to integrate MongoDB with Java client. If you have any queries, feel free to contact us or ask in the comments.

Topics:
mongo db ,nosql ,nosql db

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}