<div dir="ltr" style="text-align: justify;">
<p>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 &#8220;<b>dojCollection</b>&#8221; of &#8220;<b>dineshonjavaDB</b>&#8220;.<br />
<b></b></p>
<h2><b>Updating documents in a collection-</b></h2>
<p>For updates we can elect to update the first document found using MongoOperation&#8217;s method updateFirst or we can update all documents that were found to match the query using the method updateMulti.</p>
<p>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.</p>
<pre class="highlight">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); 
</pre>
<h2><b>Methods for executing updates for documents:</b><br />
<b></b></h2>
<p><b>1. updateFirst</b> Updates the first document that matches the query document criteria with the provided updated document.<br />
<b>2. updateMulti</b> Updates all objects that match the query document criteria with the provided updated document.</p>
<h3 class="title">Methods for the Update class</h3>
<p>The Update class can be used with a little &#8216;syntax sugar&#8217; 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.</p>
<p>Here is a listing of methods on the Update class</p>
<div class="itemizedlist">
<ul >
<li>Update <b>addToSet </b> (String key, Object value) Update using the $addToSet update modifier</li>
<li>Update <b>inc </b> (String key, Number inc) Update using the $inc update modifier</li>
<li>Update <b>pop </b> (String key, Update.Position pos) Update using the $pop update modifier</li>
<li>Update <b>pull </b> (String key, Object value) Update using the $pull update modifier</li>
<li>Update <b>pullAll </b> (String key, Object[] values) Update using the $pullAll update modifier</li>
<li>Update <b>push </b> (String key, Object value) Update using the $push update modifier</li>
<li>Update <b>pushAll </b> (String key, Object[] values) Update using the $pushAll update modifier</li>
<li>Update <b>rename </b> (String oldName, String newName) Update using the $rename update modifier</li>
<li>Update <b>set </b> (String key, Object value) Update using the $set update modifier</li>
<li>Update <b>unset </b> (String key) Update using the $unset update modifier</li>
</ul>
</div>
<p>In Spring data for MongoDB, you can use <b>save()</b>, <b>updateFirst()</b> and <b>updateMulti()</b> to update existing domain object from mongoDB database.</p>
<pre class="highlight">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); 
</pre>
<p><b>Note:</b> By default, if you didn’t define the collection name in updateFirst or updateMulti method, it will update the found object in default collection.</p>
<p>See the full example to insert document into the &#8220;<b>dojCollection</b>&#8221; of the &#8220;<b>dineshonjavaDB</b>&#8221;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/01/springdata3.png" border="0" /></div>
<h3><b>Step 1: Creating the domain class Employee</b><br />
<b>Employee.java </b></h3>
<pre class="highlight">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 + "]"; 
 } 
} 
</pre>
<h3><b>Step 2: Creating configuration file<br />
mongo-config.xml</b></h3>
<pre class="highlight"><;beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/data/mongo 
 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">; 
 
 <;!-- Default bean name is 'mongo' -->; 
 <;mongo:mongo host="localhost" port="27017"/>; 
 <;!-- Default bean name is 'mongo' -->; 
 <;mongo:mongo>; 
 <;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"/>; 
 <;/mongo:mongo>; 
 
 <;context:annotation-config/>; 
 
 <;context:component-scan base-package="com.dineshonjava.mongo">; 
 <;context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>; 
 <;/context:component-scan>; 
 
 <;!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->; 
 <;bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">; 
 <;constructor-arg ref="mongo"/>; 
 <;constructor-arg name="databaseName" value="dineshonjavaDB"/>; 
 <;/bean>; 
 
<;/beans>; 
</pre>
<h3><b>Step 3: Creating Class which inserting the document into the mongoDB.</b><br />
<b>HelloMongoDB.java</b></h3>
<pre class="highlight">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); 
 } 
} 
</pre>
<h3><b>Step 4: Running the Example</b></h3>
<p>Following code shows how to run this example<br />
<b><br />
</b> <b>HelloMongoTestApp.java</b></p>
<pre class="highlight">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!" ); 
 } 
 
} 
</pre>
<p>If everything is fine then run the above main application as Java Application we will get the following output.</p>
<div style="background-color: #ff99cc;"><b>output:</b><br />
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).<br />
log4j:WARN Please initialize the log4j system properly.<br />
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=30000]<br />
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=35000]<br />
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]<br />
Case 2&#8230;by updateFirst() &#8211; $set<br />
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=90000]<br />
Case 3&#8230;by updateFirst() &#8211; $inc<br />
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=100000]<br />
DONE!</div>
<h3><b>Download SourceCode+Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBSpringUpdateDemo.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>MongoDBSpringUpdateDemo.zip</b></a></h3>
<p><b>References</b><br />
<b><a href="http://static.springsource.org/spring-data/data-mongo/docs/1.0.0.M5/reference/html/#mongodb-template-update" target="_blank" rel="noopener">Spring data for MongoDB</a></b></p>
<p> ;</p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/spring-data-mongodb-insert-document/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/spring-data-mongodb-query-document/">next</a>>;>;</b></div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-insert-document/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-query-document/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '582'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…