<div dir="ltr" style="text-align: justify;" trbidi="on">
<div dir="ltr" style="text-align: justify;" trbidi="on">
<div dir="ltr" style="text-align: justify;" trbidi="on">In this tutorail we are going to discuss how to update data into a collection. Update can be done with update(). The <b>update()</b> takes four arguments &#8211; criteria, objectnew,upsert and multi.<br />
<b>criteria </b>&#8211; Query which specify the record to update; <br />
<b>objectnew</b>&#8211; Specify the updated information or it can be used by $ operator (i.e. $inc&#8230;).<br />
<b>upsert </b>&#8211; An upsert do update the record if match the criteria and insert record if not match.<br />
<b>multi </b>&#8211; This argument asks to updates all matching rows or just the first one(which is default). <br />
Our database name is &#8216;<b>dineshonjavaDB</b>&#8216; and our collection name is &#8216;<b>employee</b>&#8216;. Here, inserting two more records.</p>
<p>The update() method is the primary method used to modify documents in a MongoDB collection. By default, the update() method updates a <b>single</b> 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.<br />
The update() has the following syntax:</p>
<div class="highlight-javascript">
<div class="highlight">
<div align='center' id="ads-id"></div>
<pre>db.collection.update( <;query>;, <;update>;, <;options>; )
</pre>
</div>
</div>
<div class="admonition-corresponding-operation-in-sql admonition">
<div class="first admonition-title">Corresponding operation in SQL</div>
<p>The update() method corresponds to the UPDATE operation in SQL, and:</p>
<ul class="simple">
<li>the <;query>; argument corresponds to the WHERE statement, and</li>
<li>the <;update>; corresponds to the SET &#8230; statement.</li>
</ul>
<div class="last">The default behavior of the update() method updates a <b>single</b> 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.</div>
<div class="last">
</div>
</div>
<p><a href="http://docs.mongodb.org/manual/applications/update/#Updating-ModifierOperations" target="_blank">Click here</a> to know more about the Update command and its options. </p>
<p>In Java MongoDB API, you can use <b>collection.update()</b> to update an existing document. Here is some common use cases : </p>
<p><b>1. A normal way to update an existing document.</b><br />
Find empId = 10006, and update it with a new document.</div>
<pre class="highlight" name="code">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);
</pre>
<p>
<b>2. This example show the use of &#8220;$inc&#8221; modifier to increase a particular value. </b><br />
Find empId = 10006, update the &#8220;salary&#8221; value by increasing its value from 70000 to 90000, (70000 + 20000) = 90000.</p>
<pre class="highlight" name="code">BasicDBObject newDocument = new BasicDBObject().append("$inc", 
new BasicDBObject().append("salary", 20000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);
</pre>
<p>
<b>3. This example show the use of &#8220;$set&#8221; modifier to update a particular value. </b><br />
Find empId = 10006, update the &#8220;salary&#8221; from 70000 to 90000.</p>
<pre class="highlight" name="code">BasicDBObject newDocument = new BasicDBObject().append("$set", 
 new BasicDBObject().append("salary", 90000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);
</pre>
<p><b><br />
</b> <b>4. This example show the use of &#8220;multi&#8221; parameter to update a set of matched documents.</b> <br />
Find empAge= 26, update all the matched documents, &#8220;salary&#8221; value to 60000.</p>
<pre class="highlight" name="code">//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);
</pre>
<p>
See the full example and its output.</p>
<pre class="highlight" name="code">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();
 }
 
 }

}
</pre>
<p>
if every thing fine then run as java application and see the follwing output on the console.</p>
<div style="background-color: #ff99cc;"><b>output:</b><br />
Testing 1&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428bf&#8221;} , &#8220;empId&#8221; : &#8220;10007&#8221; , &#8220;empName&#8221; : &#8220;Sweety&#8221; , &#8220;salary&#8221; : 70000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c0&#8221;} , &#8220;empId&#8221; : &#8220;10008&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 60000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428be&#8221;} , &#8220;empId&#8221; : &#8220;10006&#8221; , &#8220;empName&#8221; : &#8220;Dinesh Rajput&#8221; , &#8220;salary&#8221; : 80000}<br />
Testing 2&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c1&#8221;} , &#8220;empId&#8221; : &#8220;10006&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 90000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c2&#8221;} , &#8220;empId&#8221; : &#8220;10007&#8221; , &#8220;empName&#8221; : &#8220;Sweety&#8221; , &#8220;salary&#8221; : 70000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c3&#8221;} , &#8220;empId&#8221; : &#8220;10008&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 60000}<br />
Testing 3&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c4&#8221;} , &#8220;empId&#8221; : &#8220;10006&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 90000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c5&#8221;} , &#8220;empId&#8221; : &#8220;10007&#8221; , &#8220;empName&#8221; : &#8220;Sweety&#8221; , &#8220;salary&#8221; : 70000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c6&#8221;} , &#8220;empId&#8221; : &#8220;10008&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 60000}<br />
Testing 4&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c7&#8221;} , &#8220;empId&#8221; : &#8220;10006&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 80000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c8&#8221;} , &#8220;empId&#8221; : &#8220;10007&#8221; , &#8220;empName&#8221; : &#8220;Sweety&#8221; , &#8220;salary&#8221; : 70000}<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;51055d6f8217d9c7d67428c9&#8221;} , &#8220;empId&#8221; : &#8220;10008&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : 80000}<br />
Done</div>
<p>
<b>References</b></p>
<ol style="text-align: left;">
<li><a href="http://www.mongodb.org/display/DOCS/Updating" target="_blank">How to do updating in MongoDB</a></li>
<li><a href="http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations" target="_blank">Update modifiers operations in MongoDB</a></li>
<li><a href="http://api.mongodb.org/java/current/com/mongodb/DBCollection.html#update" target="_blank">Java MongoDB APIs , DBCollection.update()</a></li>
</ol>
</div>
<p>
<b>Download Source Code + Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBUpdateDemo.zip?attredirects=0&;d=1" target="_blank"><b>MongoDBUpdateDemo.zip </b></a></p>
<div style="background-color: #ff99cc;"> ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;<b> ; ; ; ; <;<;<a href="https://dineshonjava.com/2013/01/java-mongodb-deleting-document-to.html">previous</a><;<; ; ; ; ; ; ; ; ; ; ; ; ; || <a href="https://dineshonjava.com/2013/01/introduction-to-mongodb.html">index ; </a>||  ;  ;  ;  ; >;>;<a href="https://dineshonjava.com/2013/01/java-mongodb-query-document-to-database.html">next</a>>;>;</b></div>
<p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/java-mongodb-deleting-document-to/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/java-mongodb-query-document-to-database/">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: '589'});
});
</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…