UPDATE Document In Collection In MongoDb in java






1) Program to Update Document In Collection In MongoDb in java >
package updateDocumentInCollectionInMongoDB;
/**
* Write a program to Update Document In Collection In MongoDb in java
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteResult;
public class UpdateDocumentInCollectionInMongoDb1 {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          //dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document/record in COLLECTION in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Sam");
         
          /* Insert document/record in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* Display documents of collection before UPDATING DOCUMENT in MongoDB */
          System.out.println("\nDisplay documents of collection before UPDATING DOCUMENT in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage Employee collection looks like this >
                { "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit"}
                { "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Sam"}
          */
         
         
          /** Now, let's UPDATE the document */
         
          /** Search for document whose id = 1 */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.put("id", 1);
          /** Update name to "Ankit_UPDATED"  where id = 1 */
          BasicDBObject basicDBObject_UpdatedValue = new BasicDBObject();
          basicDBObject_UpdatedValue.put("$set", new BasicDBObject().append("name", "Ankit_UPDATED"));
          /** Execute UPDATE query - To UPDATE DOCUMENT in MongoDB */
          //update method modify an existing DOCUMENT in collection in MongoDB
          WriteResult updateResult =
                     dbCollection.update(basicDBObject_SearchCondition,
                                           basicDBObject_UpdatedValue);
          System.out.println("\nExecute UPDATE query > Update "
                       + "name to 'Ankit_UPDATED' where id = 1");
          System.out.println("No of documents updated = " + updateResult.getN());
          /* Display documents of collection after UPDATING DOCUMENT in MongoDB */
          System.out.println("\nDisplay documents of collection after UPDATING DOCUMENT in MongoDB");
          DBCursor cursor = dbCollection.find();
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage Employee collection looks like this >
             { "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit_UPDATED"}
             { "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "sam"}
          */
  
  
   }
}
/* OUTPUT
Insert document1
Insert document2
Display documents of collection before UPDATING DOCUMENT in MongoDB
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Sam"}
Execute UPDATE query > Update name to 'Ankit_UPDATED' where id = 1
No of documents updated = 1
Display documents of collection after UPDATING DOCUMENT in MongoDB
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit_UPDATED"}
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Sam"}
*/


2) Program to Update multiple Documents In Collection In MongoDb in java >
package updateDocumentInCollectionInMongoDB;
/**
* Write a program to Update multiple Documents In Collection In MongoDb in java
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteResult;
//UPDATE the MULTIPLE document
public class UpdateDocumentInCollectionInMongoDb2_multipleDocument {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          //dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document/record in collection in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Ankit");
         
          /* Insert document/record in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* Display documents of collection before UPDATING MULTIPLE DOCUMENTS in MongoDB */
          System.out.println("\nDisplay documents of collection before "
                       + "UPDATING MULTIPLE DOCUMENTs in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage Employee collection looks like this >
                { "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit"}
                { "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Ankit"}
          */
         
         
          /** Now, let's UPDATE the MULTIPLE document */
         
          /** Search for document whose name = "Ankit" */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.put("name", "Ankit");
          /** Update name to 'Ankit_UPDATED' where name = 'Ankit' */
          BasicDBObject basicDBObject_UpdatedValue = new BasicDBObject();
          basicDBObject_UpdatedValue.put("$set", new BasicDBObject().append("name", "Ankit_UPDATED"));
          /** Execute MULTIPLE UPDATE query - To UPDATE MULTIPLE DOCUMENTS in collection in MongoDB*/
          //updateMulti method modify MULTIPLE DOCUMENTS in collection in MongoDB
          WriteResult updateResult =
                  dbCollection.updateMulti(basicDBObject_SearchCondition,
                                                   basicDBObject_UpdatedValue);
          System.out.println("\nExecute MULTIPLE UPDATE query - "
                       + "Update name to 'Ankit_UPDATED' where name = 'Ankit'");
          System.out.println("No of documents updated = " + updateResult.getN());
          /* Display documents of collection after UPDATING MULTIPLE DOCUMENTS in MongoDB */
          System.out.println("\nDisplay documents of collection after UPDATING MULTIPLE DOCUMENTS in MongoDB");
          DBCursor cursor = dbCollection.find();
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
         
          /** At this stage Employee collection looks like this >
                 { "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit_UPDATED"}
                 { "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Ankit_UPDATED"}
          */
  
   }
}
/* OUTPUT
Insert document1
Insert document2
Display documents of collection before UPDATING MULTIPLE DOCUMENTs in MongoDB
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Ankit"}
Execute MULTIPLE UPDATE query - Update name to 'Ankit_UPDATED' where name = 'Ankit'
No of documents updated = 2
Display documents of collection after UPDATING MULTIPLE DOCUMENTS in MongoDB
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8144"} , "id" : 1 , "name" : "Ankit_UPDATED"}
{ "_id" : { "$oid" : "585547bbad8dc81b4c7c8145"} , "id" : 2 , "name" : "Ankit_UPDATED"}
*/


3) Program to Update Document In Collection In MongoDb in java on Basis Of Multiple Conditions >
package updateDocumentInCollectionInMongoDB;
/**
* Write a program to Update Document In Collection In MongoDb in java on Basis Of Multiple Conditions
*/
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteResult;
//UPDATE document on basis of multiple conditions in java
public class UpdateDocumentInCollectionInMongoDb3_onBasisOfMultipleConditions {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          //dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
          basicDBObject1.put("salary", 100);
         
          /* Insert document1/record1 in collection in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Ankit");
          basicDBObject2.put("salary", 100);
         
          /* Insert document2/record2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* Display documents of collection before UPDATING DOCUMENT in MongoDB */
          System.out.println("\nDisplay documents of collection before UPDATING DOCUMENT in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage Employee collection looks like this >
            { "_id" : { "$oid" : "58556facad8dc83c6cddadaa"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
            { "_id" : { "$oid" : "58556facad8dc83c6cddadab"} , "id" : 2 , "name" : "Ankit" , "salary" : 100}
          */
                             
         
          /** Now, let's UPDATE the document */
         
          /** Search for document whose
          * id = 1 and
          * name = "Ankit"
          */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.append("id", 1).append("name", "Ankit");
          /** Update salary to '111'  where id = 1 and name = 'Ankit' */
          BasicDBObject basicDBObject_UpdatedValue = new BasicDBObject();
          basicDBObject_UpdatedValue.put("$set",
                                      new BasicDBObject().append("salary", 111));
          /** Execute UPDATE query - To UPDATE DOCUMENT in MongoDB*/
          WriteResult updateResult =
                      dbCollection.update(basicDBObject_SearchCondition,
                                                 basicDBObject_UpdatedValue);
          System.out.println("\nExecute UPDATE query - "
                       + "Update salary to '111'  where id = 1 and name = 'Ankit'");
          System.out.println("No of documents updated = " + updateResult.getN());
          /* Display documents of collection after UPDATING DOCUMENT in MongoDB */
          System.out.println("\nDisplay documents of collection after UPDATING DOCUMENT in MongoDB");
          DBCursor cursor = dbCollection.find();
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
         
      /** At this stage Employee collection looks like this >
       { "_id" : { "$oid" : "58556facad8dc83c6cddadaa"} , "id" : 1 , "name" : "Ankit" , "salary" : 111}
       { "_id" : { "$oid" : "58556facad8dc83c6cddadab"} , "id" : 2 , "name" : "Ankit" , "salary" : 100}   */
  
  
   }
}
/* OUTPUT
Insert document1
Insert document2
Display documents of collection before UPDATING DOCUMENT in MongoDB
{ "_id" : { "$oid" : "58556facad8dc83c6cddadaa"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
{ "_id" : { "$oid" : "58556facad8dc83c6cddadab"} , "id" : 2 , "name" : "Ankit" , "salary" : 100}
Execute UPDATE query - Update salary to '111'  where id = 1 and name = 'Ankit'
No of documents updated = 1
Display documents of collection after UPDATING DOCUMENT in MongoDB
{ "_id" : { "$oid":"58556facad8dc83c6cddadaa"} , "id" : 1 , "name" : "Ankit" , "salary" : 111}
{ "_id" : { "$oid":"58556facad8dc83c6cddadab"} , "id" : 2 , "name" : "Ankit" , "salary" : 100}
*/


4) Program to Increment Value Of field in Document In Collection In MongoDb in java >
package updateDocumentInCollectionInMongoDB;
/**
* Write a program to Increment Value Of field in Document In Collection In MongoDb in java
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteResult;
//Increment and Decrement Value In MongoDb
public class IncrementValueOfDocumentInCollectionInMongoDb {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          //dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("salary", 100);
         
          /* Insert document in collection in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* Display documents of collection before INCREMENT in MongoDB */
          System.out.println("\nDisplay documents of collection before INCREMENT in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage Employee collection looks like this >
               { "_id" : { "$oid" : "58555eb5ad8dc82c98cf958b"} , "id" : 1 , "salary" : 100}
          */
         
         
          /** Now, let's UPDATE the document to INCREMENT salary */
         
          /** Search for document whose id = 1 */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.put("id", 1);
          /** INCREMENT salary by 22 where id = 1 */
          BasicDBObject basicDBObject_UpdatedValue = new BasicDBObject();
          //Pass > $inc as key > and >
           //         BasicDBObject object with salary to be increment as value
          basicDBObject_UpdatedValue.put("$inc",
                                     new BasicDBObject().append("salary", 22));
          /** Execute UPDATE query to INCREMENT salary */
          WriteResult updateResult =
                       dbCollection.update(basicDBObject_SearchCondition,
                                                      basicDBObject_UpdatedValue);
          System.out.println("\nExecute UPDATE query to INCREMENT salary where id =1");
          System.out.println("No of documents updated = " + updateResult.getN());
          /* Display documents of collection after INCREMENT in MongoDB */
          System.out.println("\nDisplay documents of collection after INCREMENT in MongoDB");
          DBCursor cursor = dbCollection.find();
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
         
          /** At this stage Employee collection looks like this >
               { "_id" : { "$oid" : "58555eb5ad8dc82c98cf958b"} , "id" : 1 , "salary" : 122}
          */
  
   }
}
/* OUTPUT
Insert document1
Display documents of collection before INCREMENT in MongoDB
{ "_id" : { "$oid" : "58555eb5ad8dc82c98cf958b"} , "id" : 1 , "salary" : 100}
Execute UPDATE query to INCREMENT salary where id =1
No of documents updated = 1
Display documents of collection after INCREMENT in MongoDB
{ "_id" : { "$oid" : "58555eb5ad8dc82c98cf958b"} , "id" : 1 , "salary" : 122}
*/




Download >
Now, it’s time to Download maven Project :) Click here.

Read : How to Import Maven project in eclipse

OR




Summary -
So in this MongoDB tutorial we learned with example and program how to to Update Document In Collection In MongoDb in java.


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>






eEdit
Must read for you :