DZone
Database Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Database Zone > MongoDB Integration With Java

MongoDB Integration With Java

This tutorial explains how to integrate MongoDB with Java client.

Akash Tomar user avatar by
Akash Tomar
·
Jun. 21, 18 · Database Zone · Tutorial
Like (3)
Save
Tweet
12.16K Views

Join the DZone community and get the full member experience.

Join For Free

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.

MongoDB Java (programming language) Database Integration code style

Published at DZone with permission of Akash Tomar. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Kubernetes Service Types Explained In-Detail
  • SQL GROUP BY and Functional Dependencies: a Very Useful Feature
  • On Architects, Architecture, and Failures
  • Migrating Legacy Applications and Services to Low Code

Comments

Database Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo