MongoDB update is used to update document in a collection. In last tutorial, we learned about MongoDB insert with Mongo Shell and Java driver. Today we will look into MongoDB update and different options provided by Mongo Shell and Java driver.
First parameter in MongoDB update is query that gives us the target rows – for example {country:"USA"}
to get all documents where country is USA and {country:{$ne:"USA"}}
to get all the documents where country is not USA.
Second parameter in MongoDB update is used to define the list of fields to update, for example we can use {name:"Pankaj Updated"}
to update the name.
We have many mongo update parameter operators available – most widely used are $set, $inc, $currentDate.
We will look into some of these in next sections.
Now let’s see some of the MongoDB update example using Mongo shell.
-
MongoDB Update single field in a single document
1234567891011121314151617181920212223242526> db.Persons.drop()true> db.Persons.insert([... {_id:123,name:"Pankaj",country:"USA"},... {_id:456,name:"David",country:"USA"},... {_id:789,name:"Lisa",country:"India"}]... )BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 3,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]})> db.Persons.update({name:"Pankaj"},{$set: {country:"India"}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India" }{ "_id" : 456, "name" : "David", "country" : "USA" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>Notice that I am using
$set
operator to update a field value, if we don’t use that it will replace the whole document, as shown below. We can use it to replace all the fields in a particular document.123456789> db.Persons.update({name:"Pankaj"},{country:"India"})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find(){ "_id" : 123, "country" : "India" }{ "_id" : 456, "name" : "David", "country" : "USA" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }> -
MongoDB Update multiple fields
Notice that $set is used with JSON data, so if you want multiple fields to set then we can pass them as JSON.
123456789> db.Persons.update({name:"David"},{$set: {country:"India",name:"David New"}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find(){ "_id" : 123, "country" : "India" }{ "_id" : 456, "name" : "David New", "country" : "India" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }> -
MongoDB Update – Add a new field
We can use
$set
operator to add a new field to the document too, as shown below.1234567891011121314151617181920> db.Persons.drop()true> db.Persons.insert([ {_id:123,name:"Pankaj",country:"USA"}, {_id:456,name:"David",country:"USA"}, {_id:789,name:"Lisa",country:"India"}])BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 3,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]})> db.Persons.update({_id:123},{$set: {city: "San Jose"}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find({_id:123}){ "_id" : 123, "name" : "Pankaj", "country" : "USA", "city" : "San Jose" }> -
MongoDB Update subdocument
We can use mongo update dot operator to update values in a MongoDB subdocument, it’s very similar to java syntax to access methods and variables.
123456789> db.Persons.insert({_id:100,name:"Pankaj",address:{city:"San Jose",country:"USA"}})WriteResult({ "nInserted" : 1 })> db.Persons.update({_id:100},{$set: {"address.city": "Santa Clara"}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find({_id:100}){ "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } }>Notice the use of double quote for key, if double/single quote is not used then it will throw error message as
SyntaxError: Unexpected token .
. -
MongoDB Update – Remove a field
We can use MongoDB update
$unset
operator to remove a field from the document.123456789> db.Persons.find({_id:123}){ "_id" : 123, "name" : "Pankaj", "country" : "USA", "city" : "San Jose" }> db.Persons.update({_id:123},{$unset: {city: ""}})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.Persons.find({_id:123}){ "_id" : 123, "name" : "Pankaj", "country" : "USA" }> -
MongoDB Update – Insert a new document if no match found
123456789101112> db.Persons.update({name:"Pankaj"},{$set: {country:"India"}},{upsert: true})WriteResult({"nMatched" : 0,"nUpserted" : 1,"nModified" : 0,"_id" : ObjectId("53fe495bcc59ebd19e1adebb")})> db.Persons.find(){ "_id" : ObjectId("53fe495bcc59ebd19e1adebb"), "name" : "Pankaj", "country" : "India" }> -
MongoDB Update multiple documents
1234567891011121314151617181920> db.Persons.insert([{name:"Pankaj",salary:5000}, {name:"David",salary:10000}, {name:"Lisa",salary:8000}] )BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 3,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]})> db.Persons.update({salary: {$lt:9000}},{$inc: {salary: 1000}},{multi:true})WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })> db.Persons.find(){ "_id" : ObjectId("53fe49f7b1e38e3716f79117"), "name" : "Pankaj", "salary" : 6000 }{ "_id" : ObjectId("53fe49f7b1e38e3716f79118"), "name" : "David", "salary" : 10000 }{ "_id" : ObjectId("53fe49f7b1e38e3716f79119"), "name" : "Lisa", "salary" : 9000 }>Above update() has incremented the salary by 1000 for every document where salary is less than 9000.
We looked into different MongoDB document update example using Mongo Shell. Now let’s look at some of the examples using MongoDB java driver.
-
MongoDB Update Java Driver – Update Single Column in a single document
Below program shows you how to use $set in java program to make sure you are updating a single matching document.
For simplicity, test data before and after update is added as comments in the program itself.
MongoDBUpdateExample.java
123456789101112131415161718192021222324252627282930313233343536373839package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "USA" }{ "_id" : 456, "name" : "David", "country" : "USA" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*///Update single field in a single documentDBObject query = new BasicDBObject("name", "Pankaj");DBObject update = new BasicDBObject();update.put("$set", new BasicDBObject("country","India"));WriteResult result = col.update(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India" }{ "_id" : 456, "name" : "David", "country" : "USA" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*/mongo.close();}} -
MongoDB Update Java Driver – Update multiple columns
We can add multiple fields in the MongoDB Update Document to update multiple columns in a single document.
123456789101112131415161718192021222324252627282930313233343536373839package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India" }{ "_id" : 456, "name" : "David", "country" : "USA" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*///Update multiple field in a single documentDBObject query = new BasicDBObject("name", "David");DBObject update = new BasicDBObject();update.put("$set", new BasicDBObject("country","India").append("name", "David New"));WriteResult result = col.update(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India" }{ "_id" : 456, "name" : "David New", "country" : "India" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*/mongo.close();}} -
MongoDB Update Java Driver – Add a new field in a single document
Again we can use $set to add a new field in MongoDB document using update query.
123456789101112131415161718192021222324252627282930313233343536373839package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India" }{ "_id" : 456, "name" : "David New", "country" : "India" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*///Add a new field in a single documentDBObject query = new BasicDBObject("_id", 123);DBObject update = new BasicDBObject();update.put("$set", new BasicDBObject("city","San Jose"));WriteResult result = col.update(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : 123, "name" : "Pankaj", "country" : "India", "city" : "San Jose" }{ "_id" : 456, "name" : "David New", "country" : "India" }{ "_id" : 789, "name" : "Lisa", "country" : "India" }>*/mongo.close();}} -
MongoDB Update Java Driver – Update subdocument
Just like shell commands, we can use dot operator with $set to update sub-documents using update query.
1234567891011121314151617181920212223242526272829303132333435package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "city" : "San Jose", "country" : "USA" } }>*///Update sub-document in a single documentDBObject query = new BasicDBObject("_id", 100);DBObject update = new BasicDBObject();update.put("$set", new BasicDBObject("address.city","Santa Clara"));WriteResult result = col.update(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } }>*/mongo.close();}} -
MongoDB Update Java Driver – Remove a field
We use $unset update option to remove a field from MongoDB document, we can remove fields from subdocument too.
1234567891011121314151617181920212223242526272829303132333435package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } }>*///Remove a field in a single documentDBObject query = new BasicDBObject("_id", 100);DBObject update = new BasicDBObject();update.put("$unset", new BasicDBObject("address.city",""));WriteResult result = col.update(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } }>*/mongo.close();}} -
MongoDB Update Java Driver – Insert a new document if no match found
We need to pass upsert parameter value as true for this, an example is shown below.
123456789101112131415161718192021222324252627282930313233343536package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } }>*///insert document if no match foundDBObject query = new BasicDBObject("name", "Lisa");DBObject update = new BasicDBObject();update.put("$set", new BasicDBObject("city","San Jose"));WriteResult result = col.update(query, update, true, false);/*** Test Data - After update* > db.Persons.find(){ "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } }{ "_id" : ObjectId("54020800cc59ebd19e1adebc"), "name" : "Lisa", "city" : "San Jose" }>*/mongo.close();}} -
MongoDB Update Java Driver – Update multiple documents
MongoDB Java Driver API provides updateMulti method that we can use to update multiple documents, in below example we are updating all the documents salary by 1000 where it’s less than 9000. This is also one of the example of
$inc
update option.123456789101112131415161718192021222324252627282930313233343536373839package com.journaldev.mongodb.main;import java.net.UnknownHostException;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;import com.mongodb.WriteResult;public class MongoDBUpdateExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);DB db = mongo.getDB("journaldev");DBCollection col = db.getCollection("Persons");/*** Test Data - Before update* > db.Persons.find(){ "_id" : ObjectId("5402088bb1e38e3716f7911a"), "name" : "Pankaj", "salary" : 5000 }{ "_id" : ObjectId("5402088bb1e38e3716f7911b"), "name" : "David", "salary" : 10000 }{ "_id" : ObjectId("5402088bb1e38e3716f7911c"), "name" : "Lisa", "salary" : 8000 }>*///Update multiple document - $inc exampleDBObject query = new BasicDBObject("salary", new BasicDBObject("$lt", 9000));DBObject update = new BasicDBObject();update.put("$inc", new BasicDBObject("salary",1000));WriteResult result = col.updateMulti(query, update);/*** Test Data - After update* > db.Persons.find(){ "_id" : ObjectId("5402088bb1e38e3716f7911a"), "name" : "Pankaj", "salary" : 6000 }{ "_id" : ObjectId("5402088bb1e38e3716f7911b"), "name" : "David", "salary" : 10000 }{ "_id" : ObjectId("5402088bb1e38e3716f7911c"), "name" : "Lisa", "salary" : 9000 }>*/mongo.close();}}
That’s all for MongoDB Update document examples using Mongo shell as well as MongoDB java driver, do let me know if you face any problems with it.