Web Programming TutorialsLearn How to Update and Delete From a Collection using MongoDB

Learn How to Update and Delete From a Collection using MongoDB

Collection using MongoDB

In this chapter, we are going to use the MongoDB JDBC connection (explained in the previous article) in order to connect MongoDB database with JAVA. After successfully connecting MongoDB with JAVA, we are going to create a collection, insert, modify and delete documents into this collection through JAVA programming language.

MongoDbJdbcConnection.java

package com.eduonix.db;

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

public class MongoDbJdbcConnection {

	public static DB getMongoDBConnection (String host, int port, String dBName){
		DB db = null;
		try {
			/**** Connect to the MongoDB ****/
			// Since 2.10.0, uses MongoClient 27017
			MongoClient mongodb  = new MongoClient(host, port);
 
			/**** Get database ****/
			// if database doesn't exists, MongoDB will create it for us
			db = mongodb.getDB(dBName);
			System.out.println("Connect to database is success "+db);
			
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
		return db;
	}
}

MongoDB – Creation, Selection and modification of a document in a collection
Using the class ‘MongoDbJdbcConnection.java’, we will be able to connect to MongoDB by simply calling the static method getMongoDBConnection which accepts three arguments i.e. host name, port number and database name. This method will return a DB class object. By using this DB object, we are going to first create and select a collection followed by the modification of a document in this collection through JAVA Programming.

Syntaxes

  • To create a collection, we can use the ‘createCollection ()’ method of com.mongodb.DB class.
  • To get or select a collection from the database, we can use the ‘getCollection ()’ method of com.mongodb.DBCollection class.
  • To insert a document into MongoDB, we can use the ‘insert ()’ method of com.mongodb.DBCollection class.
  • To modify or update a document into MongoDB, we can use the ‘update ()’ method of com.mongodb.DBCollection class.

MongoDbUpdateDemo.java

package com.eduonix.db;

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

public class MongoDbUpdateDemo {
	
	public static void main(String args[]){
		String CollectionName ="MyCollection10";
		
		DB db = MongoDbJdbcConnection.getMongoDBConnection("localhost", 27017, "dbtest");
		/**
		 * Creating and Inserting Records in MongoDB.
		 */
		DBObject dbObject = new BasicDBObject("title", "MongoDBTutorials").append("description", "No-SQL Database")
				.append("likes", 100000).append("url", "https://www.mongodb.com/").append("Tutorial", "Eduonix");

		db.createCollection(CollectionName, dbObject);
		
		/**
		 * Selecting Records from MongoDB
		 */
		DBCollection coll = db.getCollection(CollectionName);
		coll.insert(dbObject);
		//coll.insert(dbObject2);
		System.out.println("Collection has created successfully");
		/**
		 * Displaying available records.
		 */
		DBCursor cursor = coll.find();
		int index = 1;
		while (cursor.hasNext()) {
			System.out.println("Inserted Document: " + index);
			System.out.println(cursor.next());
			index++;
		}
		/**
		 * Modify a Document present in a Collection.
		 */
		DBCursor cursor1 = coll.find();
		DBObject dbObjectQuery = new BasicDBObject("title", "MongoDBTutorials");
        while (cursor1.hasNext()) { 
           DBObject updateDocument = cursor1.next();
           updateDocument.put("likes","9999999");
           updateDocument.put("description","No-SQL Database with high performance!");
           coll.update(dbObjectQuery,updateDocument); 
        }
			
        System.out.println("Document has updated successfully");
        DBCursor cursor2 = coll.find();
        int i = 1;
        while (cursor2.hasNext()) { 
           System.out.println("Updated Document: "+i); 
           System.out.println(cursor2.next()); 
           i++;
        }
	}
}

Before executing this program, make sure that the MongoDB instance is running on your local or remote machine. Here, the MongoDB instance is running on the local machine at port 27017.

Explanation of Code

  • Firstly, we are connecting the MongoDB client by passing three arguments to the static getMongoDBConnection method of ‘MongoDbJdbcConnection.java’ class. This will return a DB class instance of a MongoDB database into ‘db’ instance variable.
  • Next, we are creating instance of ‘DBObject’ through ‘BasicDBObject’ class that helps to create the schema definition to be inserted in the collection.
  • Next, we are creating collection through ‘db.createCollection (“MyCollection10”, dbObject);’ method.
  • Next, we are going to select this collection ‘MyCollection10’ through ‘db.getCollection (“MyCollection10”);’ method which returns the instance into ‘coll’ instance variable.
  • Through ‘coll’ instance variable, we can use ‘coll.insert (dbObject);’ to insert the DBObject instance which we have created before. At this step, a document has successfully inserted into the MongoDB.
  • Now, we are using ‘DBCursor’ class which returns the cursor to iterate over the documents and display those documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method.
  • Next, we are again using ‘DBCursor’ class which returns the cursor to iterate over the documents and modify or update those documents present in the current collection through ‘coll.update (dbObjectQuery, updateDocument)’ method.
  • Next, we are again using ‘DBCursor’ class which returns the cursor to iterate over the documents and display the modified documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method.

Output
When we execute above JAVA program, it will connect to the MongoDB and do the creation, selection and retrieving operations on the collection ‘MyCollection10’ followed by the modification of a document present in this collection as shown on the console.

Feb 23, 2017 6:10:49 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connect to database is success DB{name='dbtest'}
Feb 23, 2017 6:10:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Feb 23, 2017 6:10:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:31}] to localhost:27017
Feb 23, 2017 6:10:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=2824198}
Feb 23, 2017 6:10:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:32}] to localhost:27017
Collection has created successfully
Inserted Document: 1
{ "_id" : { "$oid" : "58af6bfa7d1fcb0fb0e5fa47"} , "title" : "MongoDBTutorials" , "description" : "No-SQL Database" , "likes" : 100000 , "url" : "https://www.mongodb.com/" , "Tutorial" : "Eduonix"}
Document has updated successfully
Updated Document: 1
{ "_id" : { "$oid" : "58af6bfa7d1fcb0fb0e5fa47"} , "title" : "MongoDBTutorials" , "description" : "No-SQL Database with high performance!" , "likes" : "9999999" , "url" : "https://www.mongodb.com/" , "Tutorial" : "Eduonix"}

MongoDB – Deletion of a document in a collection
Using the class ‘MongoDbJdbcConnection.java’, we will be able to connect to MongoDB by simply calling the static method getMongoDBConnection, which accepts three arguments i.e. host name, port number and database name. This method will return DB object. By using this DB object, we are going to select a collection followed by the deletion of a document from this collection through JAVA Programming.

Syntaxes

  • To get or select a collection from the database, we can use the ‘getCollection ()’ method of com.mongodb.DBCollection class.
  • To delete a document into MongoDB, we can use the ‘remove ()’ method of com.mongodb.DBCollection class.

MongoDbDeleteDemo.java

package com.eduonix.db;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class MongoDbDeleteDemo {

	public static void main(String args[]){
		String CollectionName ="MyCollection10";
		
		DB db = MongoDbJdbcConnection.getMongoDBConnection("localhost", 27017, "dbtest");
		/**
		 * Selecting Records from MongoDB
		 */
		DBCollection coll = db.getCollection(CollectionName);
		System.out.println("Collection has selected successfully");
		/**
		 * Displaying available records.
		 */
		DBCursor cursor = coll.find();
		int index = 1;
		while (cursor.hasNext()) {
			System.out.println("Displaying available Documents: " + index);
			System.out.println(cursor.next());
			index++;
		}
		/**
		 * Modify a Document present in a Collection.
		 */
		
	    DBObject myDocument = coll.findOne();
        coll.remove(myDocument);
         index=1;
        while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+index); 
            System.out.println(cursor.next()); 
            index++;
         }
			
         System.out.println("Document has deleted successfully");
        
	}
}

Before executing this program, make sure that the MongoDB instance is running on your local or remote machine. Here, the MongoDB instance is running on the local machine at port 27017.

Explanation of Code

  • Firstly, we are connecting the MongoDB client by passing three arguments to the static getMongoDBConnection method of ‘MongoDbJdbcConnection.java’ class. This will return a DB class instance of a MongoDB database into ‘db’ instance variable.
  • Next, we are going to select this collection ‘MyCollection10’ through ‘db.getCollection (“MyCollection10”);’ method which returns the instance into ‘coll’ instance variable.
  • Next, we are finding a document through coll.findOne () method and calling the remove () method to delete this document from the selected selection.
  • Now, we are using ‘DBCursor’ class which returns the cursor to iterate over the documents and display those documents present in the current collection through ‘DBCursor cursor = coll.find ();’ method.

Output
When we execute above JAVA program, it will connect to the MongoDB and perform the select operation on the collection ‘MyCollection10’ followed by the deletion of a document present in this collection as shown on the console.

Feb 23, 2017 6:46:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connect to database is success DB{name='dbtest'}
Collection has selected successfully
Feb 23, 2017 6:46:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:49}] to localhost:27017
Feb 23, 2017 6:46:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=1998092}
Feb 23, 2017 6:46:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Feb 23, 2017 6:46:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:50}] to localhost:27017
Document has deleted successfully

Source code for the Update and Delete From a Collection using MongoDB

Conclusion: –
In this tutorial, we have created a JDBC connection to MongoDB database through a static method of a generic class that accepts connection arguments. After JDBC connection, we have created a collection to do the modification and deletion operation on a document present in a collection of MongoDB.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -