MongoDB Integration with Java

存储架构 2018-06-22

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


org.mongodb
mongo-java-driver
2.10.1

 

Now let’s start 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

   = 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
or ask in the comments.

DZone

责编内容by:DZone (源链)。感谢您的支持!

您可能感兴趣的

服务治理深入浅出(2)- 远程方法调用的实现... 需求 在了解了前面我们关于 服务治理出现的必要性 之后。我们知道服务治理是建立在众多“服务”基础之上的,那么,第一步,打通这些服务是基础,也就是我们...
Android APT 技术浅谈 通过学习与使用square公司的开源项目javapoet,来实现仓库层动态生成代码 安卓AOP三剑客: APT, AspectJ, Javassi...
关于java内存访问重排序的思考 @author: stormma @date 2018/03/30 生命不息,奋斗不止 前言 且看一段测试代码, 在不借助外界工具的条件下得出...
Oracle宣布新的Java Champions 看新闻很累?看技术新闻更累?试试 下载InfoQ手机客户端 ,每天上下班路上听新闻,有趣还有料! Oracle宣布了2017年 新接纳的...
Null Behavior in Java This probably looks duplicate of other questions on SO. But, I was wondering th...