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 :
{ "_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 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.
MongoClient mongo = new MongoClient( "localhost" , 27017 ); // If we use older version than Mongo mongo = new Mongo("localhost", 27017);
3. Connection with database
Now connect with database , if our database doesn’t exist than mongo will create new databse.
DB database = mongoClient.getDB("testdb");
If we are using mongo in secure mode than 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 is already exist with following code.
mongoClient.getDatabaseNames().forEach(System.out::println);
4. Mongo Collection
Now create collection which is equivalent to table in RDBMS. We can make collection as:
database.createCollection("users", null);
Get and print all existing collection for selected DB.
database.getCollectionNames().forEach(System.out::println);
5. Insert Document
Now we will save a document (data) in 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 database.
{ "_id" : ObjectId("5b0d226b31a5f6595a7034de"), "firstName" : "Dharam", "lastName" : "Rajput" }
6. Update Document
Let’s assume we have 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 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 = new BasicDBObject().append("firstName", "Dharmendra"); DBCursor findCursor = collection.find(findQuery); while (findCursor.hasNext()) { System.out.println(findCursor.next()); } } catch (Exception e) { e.printStackTrace(); } } }
Hope you liked the tutorial on how to integrate MongoDB with Java client. If you have any queries, feel free to contact us.