Spring Data MongoDB : Update document

In this tutorial we will discuss about the updating the document to the mongoDB. Document is same as a row in the table of relational database. In the our example we will update a document to "dojCollection" of "dineshonjavaDB".

Updating documents in a collection-
For updates we can elect to update the first document found using MongoOperation's method updateFirst or we can update all documents that were found to match the query using the method updateMulti.

Here is an example of an update of salary of all employees where employee age is 24 and we are adding a one time $50.00 bonus to the salary using the $inc operator.
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;

          ...

  WriteResult wr = mongoTemplate.updateMulti(
new Query(where("empAge").is(24)),new Update().inc("salary", 50.00),Employee.class);
Methods for executing updates for documents:
1. updateFirst Updates the first document that matches the query document criteria with the provided updated document.
2. updateMulti Updates all objects that match the query document criteria with the provided updated document.

Methods for the Update class

The Update class can be used with a little 'syntax sugar' as its methods are meant to be chained together and you can kickstart the creation of a new Update instance via the static method public static Update update(String key, Object value) and using static imports.
Here is a listing of methods on the Update class
  • Update addToSet (String key, Object value) Update using the $addToSet update modifier
  • Update inc (String key, Number inc) Update using the $inc update modifier
  • Update pop (String key, Update.Position pos) Update using the $pop update modifier
  • Update pull (String key, Object value) Update using the $pull update modifier
  • Update pullAll (String key, Object[] values) Update using the $pullAll update modifier
  • Update push (String key, Object value) Update using the $push update modifier
  • Update pushAll (String key, Object[] values) Update using the $pushAll update modifier
  • Update rename (String oldName, String newName) Update using the $rename update modifier
  • Update set (String key, Object value) Update using the $set update modifier
  • Update unset (String key) Update using the $unset update modifier
 In Spring data for MongoDB, you can use save(), updateFirst() and updateMulti() to update existing domain object from mongoDB database.
Employee employee = new Employee("...");
 
 //update employee object into entity collection
 mongoOperation.save(employee);
 
 //update employee object into "newCollection" collection
 mongoOperation.save("newCollection",employee);
 
 //update first found record, empName field, where empId = 1004,
 //from your default collection
 mongoOperation.updateFirst(
  new Query(Criteria.where("empId").is(1004)),
  Update.update("empName", "new name"));
 
 //update first found record, empName field, where empId = 1004,  
 //from collection named "employee"
 mongoOperation.updateFirst("employee",
  new Query(Criteria.where("empId").is(1004)),
  Update.update("empName", "new name"));
 
 //update all found records, salary field, where empAge = "24",  
 //from collection named "employee"
 mongoOperation.updateMulti("employee",
  new Query(Criteria.where("empAge").is(24)),
  Update.update("salary", 70000));
 
 //update first found record, age field, where empId = 1001, using $inc  
 Update updateAge = new Update();
 updateAge.inc("age", 10);
 
 mongoOperation.updateFirst("employee",
  new Query(Criteria.where("empId").is(1001)), updateAge);

Note: By default, if you didn’t define the collection name in updateFirst or updateMulti method, it will update the found object in default collection.

See the full example to insert document into the "dojCollection" of the "dineshonjavaDB"

Step 1: Creating the domain class Employee
Employee.java  
package com.dineshonjava.mongo.dto;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author Dinesh Rajput
 *
 */
@Document
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}

Step 2: Creating configuration file
mongo-config.xml



  
 
 <mongo:mongo host="localhost" port="27017"/>
  
 
  <mongo:options connections-per-host="100"
   threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 
 
 <context:annotation-config/>
     
    
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    
    
 
   
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   
    


Step 3: Creating Class which inserting the document into the mongoDB.
HelloMongoDB.java
package com.dineshonjava.mongo.main;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  // Case1 - insert a employee, put "DOJ" as collection name 
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Anamika Rajput");
  employee.setSalary(30000);
  employee.setEmpAge(23);
  
  mongoOperations.save(employee, "DOJ");
     
  // find
  Employee employee1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employee1);
   
  // Update employee object, salary
  employee1.setSalary(35000);
  mongoOperations.save(employee1, "DOJ");
   
  // find
  Employee employeeupdated = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employeeupdated);
  
  // Case 2 ... update salary field, $set
  Employee employee2 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"orders");
  System.out.println(employee2);
     
  // Update employee object, salary
  System.out.println("Case 2...by updateFirst() - $set");
   
  mongoOperations.updateFirst(query(where("empId").is(1001)), Update.update("salary", 40000),"orders");
    
  // find
  Employee employeeupdated1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"orders");
  System.out.println(employeeupdated1);
  
  // Case 3 ... update salary field, $inc
  System.out.println("Case 3...by updateFirst() - $inc");
  Update updateSalary = new Update();
  updateSalary.inc("salary", 1000);
  mongoOperations.updateFirst(query(where("empId").is(1001)), updateSalary, "orders");
  Employee employee3 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class);
  System.out.println(employee3);
 }
}

Step 4: Running the Example
Following code shows how to run this example

HelloMongoTestApp.java
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.

output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=30000]
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=35000]
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]
Case 2...by updateFirst() - $set
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=90000]
Case 3...by updateFirst() - $inc
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=100000]
DONE!

Download SourceCode+Libs
MongoDBSpringUpdateDemo.zip

References
Spring data for MongoDB


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


No comments:

Post a Comment