MongoDB- MongoDB with Java

MongoDB -Java Example

To use MongoDB in our Java programs, we need MongoDB JDBC driver. Follow the below steps to do so.

Steps to Connect with MongoDB Using Java

1.Create Java Project using Elipse Convet that into Maven Project

2. Download mongo-java driver from **github. Or declare mongo-java driver in pom.xml**

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

3. Write a Java class to connect with MongoDB & perform operations

package core;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

public class MongoDBConnect {
	public static void main(String[] args) {
 try {
 	/**** Connect to MongoDB ****/
 	// Since 2.10.0, uses MongoClient
 	MongoClient mongo = new MongoClient("localhost", 27017);

 	/**** Get database ****/
 	// if database doesn't exists, MongoDB will create it for you
 	DB db = mongo.getDB("smlcodes");

 	/**** Get collection / table from 'testdb' ****/
 	// if collection doesn't exists, MongoDB will create it for you
 	DBCollection table = db.getCollection("user");

 	if (mongo != null) {
 System.out.println("============\n MongoDB Connected!!! \n===========");
  System.out.println("Database Name : " + db.getName());
  System.out.println("Collection : " + table.getName());
 	}

 } catch (UnknownHostException e) {
 	e.printStackTrace();
 } catch (MongoException e) {
 	e.printStackTrace();
 }
	}
}

-----------------------------------
 MongoDB Connected!!! 
===========
Database Name : smlcodes
Collection : user

3.1 MongoDB with Java

1.Mongo Connection

Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.

// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);

// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient( "localhost" , 27017 );

2.Mongo Database

Get database. If the database doesn’t exist, MongoDB will create it for you.

DB db = mongo.getDB("database name");

If MongoDB in secure mode, authentication is required

boolean auth = db.authenticate("username", "password".toCharArray());

Display all databases.

List<String> dbs = mongo.getDatabaseNames();
for(String db : dbs){
	System.out.println(db);
}

3.Mongo Collection

Get collection / table.

DB db = mongo.getDB("testdb");
DBCollection table = db.getCollection("user");

Display all collections from selected database.

DB db = mongo.getDB("testdb");
Set<String> tables = db.getCollectionNames();

for(String coll : tables){
	System.out.println(coll);
}

Steps to develop any MongoDB Application

1.Connect with MongoDB Server

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

2.Connect with Database

DB db = mongoClient.getDB("smlcodes");

3.Get the Collection , on which collection you want to work

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

4.Get Document Object to perform CURD operaions on Document

BasicDBObject document = new BasicDBObject();


1.MongoDB Authenetication Example

Add user to smlcodes Collection for testing purpose

db.createUser(
                {
                  user: "admin",
                  pwd: "admin",
                  roles: [
                     {role: "readWrite", db: "smlcodes"}
                          ]
                  }
           )

Example

import com.mongodb.DB;
import com.mongodb.MongoClient;

public class MongoDB_Authentication {
	public static void main(String args[]) {
 try {
 	// To connect to mongodb server
 	MongoClient mongoClient = new MongoClient("localhost", 27017);

 	// Now connect to your databases
 	DB db = mongoClient.getDB("smlcodes");
 	System.out.println("Connect to database successfully");
 	boolean auth = db.authenticate("admin", "admin".toCharArray());
 	System.out.println("Authentication: " + auth);

 } catch (Exception e) {
 	System.err.println(e.getClass().getName() + ": " + e.getMessage());
 }
	}
}

MongoDB Java Complete Example

package core;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
public class MongoDB_Insert {
	public static void main(String[] args) {

 try {

 	Mongo mongo = new Mongo("localhost", 27017);
 	DB db = mongo.getDB("smlcodes");

 	DBCollection collection = db.getCollection("users");
 	collection.remove(new BasicDBObject());

 	// 1. BasicDBObject example
 	System.out.println("1.BasicDBObject example...");
 	System.out.println("===========================");
 	BasicDBObject document = new BasicDBObject();
 	document.put("username", "satyajohnny");
 	document.put("password", "password254");

 	BasicDBObject documentDetail = new BasicDBObject();
 	documentDetail.put("street", "RAMALAYAM");
 	documentDetail.put("city", "VIJAYAWADA");
 	documentDetail.put("state", "ANDHRA PRADESH");
 	document.put("address", documentDetail);
 	collection.insert(document);

 	DBCursor cursorDoc = collection.find();
 	while (cursorDoc.hasNext()) {
  System.out.println(cursorDoc.next());
 	}
 	collection.remove(new BasicDBObject());

 	// 2. BasicDBObjectBuilder example
 	System.out.println("\n\n 2.BasicDBObjectBuilder Insert");
 	System.out.println("===========================");
 	BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
                                          .add("username", "Anil")
                                          .add("password",	"Anigirekula123");

 	BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
                                 .add("street", "NTR STREET")
          .add("city", "HYDERABAD").add("state", "TN");
 	documentBuilder.add("detail", documentBuilderDetail.get());
 	collection.insert(documentBuilder.get());

 	DBCursor cursorDocBuilder = collection.find();
 	while (cursorDocBuilder.hasNext()) {
  System.out.println(cursorDocBuilder.next());
 	}
 	collection.remove(new BasicDBObject());

 	// 3. Map example
 	System.out.println("\n\n 3.MAP Insert");
 	System.out.println("===========================");
 	Map<String, Object> documentMap = new HashMap<String, Object>();
 	documentMap.put("username", "mapuser");
 	documentMap.put("password", "mapassword");

 	Map<String, Object> documentMapDetail = new HashMap<String, Object>();
 	documentMapDetail.put("street", "JAMES STREET");
 	documentMapDetail.put("city", "GEORGIO");
 	documentMapDetail.put("state", "U.S");
 	documentMap.put("detail", documentMapDetail);
 	collection.insert(new BasicDBObject(documentMap));

 	DBCursor cursorDocMap = collection.find();
 	while (cursorDocMap.hasNext()) {
  System.out.println(cursorDocMap.next());
 	}
 	collection.remove(new BasicDBObject());

 	// 4. JSON parse example
 	System.out.println("\n\n 4.JSON Insert");
 	System.out.println("===========================");

	String json = "{'username' : 'jsonuser','password' : 'JsonPass',"
	+ "'detail' : {'street' : 'FIGHTCLUB STREET', 'city' : 'MELBORN', 'state' : 'AUS'}}}";

 	DBObject dbObject = (DBObject) JSON.parse(json);
 	collection.insert(dbObject);

 	DBCursor cursorDocJSON = collection.find();
 	while (cursorDocJSON.hasNext()) {
  System.out.println(cursorDocJSON.next());
 	}
 	collection.remove(new BasicDBObject());

 } catch (UnknownHostException e) {
 	e.printStackTrace();
 } catch (MongoException e) {
 	e.printStackTrace();
 }

	}
}
//Output
1.BasicDBObject example...
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c09"} , "username" : "satyajohnny" , "password" : "password254" , "address" : { "street" : "RAMALAYAM" , "city" : "VIJAYAWADA" , "state" : "ANDHRA PRADESH"}}


 2.BasicDBObjectBuilder Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0a"} , "username" : "Anil" , "password" : "Anigirekula123" , "detail" : { "street" : "NTR STREET" , "city" : "HYDERABAD" , "state" : "TN"}}


 3.MAP Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0b"} , "password" : "mapassword" , "detail" : { "city" : "GEORGIO" , "street" : "JAMES STREET" , "state" : "U.S"} , "username" : "mapuser"}


 4.JSON Insert
===========================
{ "_id" : { "$oid" : "589b07a32989f6de61c17c0c"} , "username" : "jsonuser" , "password" : "JsonPass" , "detail" : { "street" : "FIGHTCLUB STREET" , "city" : "MELBORN" , "state" : "AUS"}}

In above we are removing inserted Object for display purpose only

collection.remove(new BasicDBObject());

Similarly we can perform CURD operations using below methods in the same way


Update Operation

Update a document where -username”=”satya” to SatyaKaveti.

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

BasicDBObject query = new BasicDBObject();
query.put("username", "satya");

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("username", "SatyaKaveti");

BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);

table.update(query, updateObj);

Find/Query/Search Operation

Find document where -username =satya”, and display it with DBCursor

BCollection table = db.getCollection("user");

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("username ", " satya ");

DBCursor cursor = table.find(searchQuery);

while (cursor.hasNext()) {
	System.out.println(cursor.next());
}

Delete Operation
Find document where -username =satya”, and delete it.

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

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("username ", " satya ");

table.remove(searchQuery);

References

http://www.javatpoint.com/mongodb-tutorial

https://docs.mongodb.com/v3.2/tutorial/

http://www.mkyong.com/tutorials/java-mongodb-tutorials/

https://www.tutorialspoint.com/mongodb/mongodb_environment.htm