Your Ads Belongs Here

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;
import static;
import static;


  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;
 //update employee object into "newCollection" collection"newCollection",employee);
 //update first found record, empName field, where empId = 1004,
 //from your default collection
  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"
  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"
  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();"age", 10);
  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  
package com.dineshonjava.mongo.dto;


 * @author Dinesh Rajput
public class Employee {
 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;
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";

Step 2: Creating configuration file

<beans xmlns:context="" xmlns:mongo="" xmlns:p="" xmlns:xsi="" xmlns="" xsi:schemalocation="">
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
  <mongo:options connections-per-host="100"
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
   <bean class="" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>

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

import static;
import static;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

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

Step 4: Running the Example
Following code shows how to run this example
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;

 * @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");
   System.out.println( "DONE!" );


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

log4j:WARN No appenders could be found for logger (
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 updateFirst() - $set
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=90000]
Case updateFirst() - $inc
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=100000]

Download SourceCode+Libs

Spring data for MongoDB

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

No comments:

Post a Comment