Java MongoDB Updating a Document to Database

In this tutorail we are going to discuss how to update data into a collection. Update can be done with update(). The update() takes four arguments - criteria, objectnew,upsert and multi.
criteria - Query which specify the record to update;
objectnew- Specify the updated information or it can be used by $ operator (i.e. $inc...).
upsert - An upsert do update the record if match the criteria and insert record if not match.
multi - This argument asks to updates all matching rows or just the first one(which is default).
Our database name is 'dineshonjavaDB' and our collection name is 'employee'. Here, inserting two more records.

The update() method is the primary method used to modify documents in a MongoDB collection. By default, the update() method updates a single document, but by using the multi option, update() can update all documents that match the query criteria in the collection. The update() method can either replace the existing document with the new document or update specific fields in the existing document.
The update() has the following syntax:
db.collection.update( <query>, <update>, <options> )
Corresponding operation in SQL
The update() method corresponds to the UPDATE operation in SQL, and:
  • the <query> argument corresponds to the WHERE statement, and
  • the <update> corresponds to the SET ... statement.
The default behavior of the update() method updates a single document and would correspond to the SQL UPDATE statement with the LIMIT 1. With the multi option, update() method would correspond to the SQL UPDATE statement without the LIMIT clause.

Click here to know more about the Update command and its options.

In Java MongoDB API, you can use collection.update() to update an existing document. Here is some common use cases :

1. A normal way to update an existing document.
Find empId = 10006, and update it with a new document.
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("empId", 10006);
newDocument.put("empName", "Dinesh Rajput");
newDocument.put("salary", 70000);
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

2. This example show the use of "$inc" modifier to increase a particular value.
Find empId = 10006, update the "salary" value by increasing its value from 70000 to 90000, (70000 + 20000) = 90000.
BasicDBObject newDocument = new BasicDBObject().append("$inc", 
new BasicDBObject().append("salary", 20000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

3. This example show the use of "$set" modifier to update a particular value.
Find empId = 10006, update the "salary" from 70000 to 90000.
BasicDBObject newDocument = new BasicDBObject().append("$set", 
 new BasicDBObject().append("salary", 90000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

4. This example show the use of "multi" parameter to update a set of matched documents.
Find empAge= 26, update all the matched documents, "salary" value to 60000.
//find empAge= 26 , update all matched documents , "salary" value to 60000
BasicDBObject updateQuery = new BasicDBObject().append("$set", 
 new BasicDBObject().append("salary", "60000"));
 
//both methods are doing the same thing.
//collection.updateMulti(new BasicDBObject().append("empAge", "26"), updateQuery);
collection.update(new BasicDBObject().append("empAge", "26"), updateQuery, false, true);

See the full example and its output.

package com.dineshonjava.mongo.test;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * @author Dinesh Rajput
 *
 */
public class UpdateDocumentDemo {

 public static void printAllDocuments(DBCollection collection){
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }
 
 public static void removeAllDocuments(DBCollection collection){
  collection.remove(new BasicDBObject());
 }
 
 public static void insertDummyDocuments(DBCollection collection){
  BasicDBObject document = new BasicDBObject();
  document.put("empId", "10006");
  document.put("empName", "Dinesh");
  document.put("salary", 70000);
 
  BasicDBObject document2 = new BasicDBObject();
  document2.put("empId", "10007");
  document2.put("empName", "Sweety");
  document2.put("salary", 70000);
 
  BasicDBObject document3 = new BasicDBObject();
  document3.put("empId", "10008");
  document3.put("empName", "Dinesh");
  document3.put("salary", 60000);
 
  collection.insert(document);
  collection.insert(document2);
  collection.insert(document3);
 }
 
 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
 
  // get a single collection
  DBCollection collection = db.getCollection("employee");
 
  System.out.println("Testing 1...");
  insertDummyDocuments(collection);
  //find empId = 10006, and update it with new document
  BasicDBObject newDocument = new BasicDBObject();
  newDocument.put("empId", "10006");
  newDocument.put("empName", "Dinesh Rajput");
  newDocument.put("salary", 80000);
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 2...");
  insertDummyDocuments(collection);
  //find empId = 10006 and increase its "salary" value by 90000
  BasicDBObject newDocument2 = new BasicDBObject().append("$inc", 
    new BasicDBObject().append("salary", 20000));
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument2);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 3...");
  insertDummyDocuments(collection);
  //find empId = 10006 and update salary to from 70000 to 90000
  BasicDBObject newDocument3 = new BasicDBObject().append("$set", 
    new BasicDBObject().append("salary", 90000));
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument3);
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 4...");
  insertDummyDocuments(collection);
  //find empName = Dinesh , update all matched documents , salary value to 80000
  BasicDBObject updateQuery = new BasicDBObject().append("$set", 
    new BasicDBObject().append("salary", 80000));
 
  //both method are same
  //collection.updateMulti(new BasicDBObject().append("empName", "Dinesh"), updateQuery);
 
  collection.update(new BasicDBObject().append("empName", "Dinesh"), updateQuery, false, true);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}

if every thing fine then run as java application and see the follwing output on the console.
output:
Testing 1...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428bf"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c0"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428be"} , "empId" : "10006" , "empName" : "Dinesh Rajput" , "salary" : 80000}
Testing 2...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c1"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 90000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c2"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c3"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
Testing 3...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c4"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 90000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c5"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c6"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
Testing 4...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c7"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 80000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c8"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c9"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 80000}
Done

References

  1. How to do updating in MongoDB
  2. Update modifiers operations in MongoDB
  3. Java MongoDB APIs , DBCollection.update()

Download Source Code + Libs
MongoDBUpdateDemo.zip

                             <<previous<<             || index  ||         >>next>>



No comments:

Post a Comment