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.
Table of Contents
- 1 MongoDB update
- 1.1 MongoDB Update Document Operators
- 1.2 MongoDB Update Document Example
- 1.3 MongoDB Update single field in a single document
- 1.4 MongoDB Update multiple fields
- 1.5 MongoDB Update – Add a new field
- 1.6 MongoDB Update subdocument
- 1.7 MongoDB Update – Remove a field
- 1.8 MongoDB Update – Insert a new document if no match found
- 1.9 MongoDB Update multiple documents
- 1.10 MongoDB update document example using Java Driver
- 1.11 MongoDB Update Java Driver – Update Single Column in a single document
- 1.12 MongoDB Update Java Driver – Update multiple columns
- 1.13 MongoDB Update Java Driver – Add a new field in a single document
- 1.14 MongoDB Update Java Driver – Update subdocument
- 1.15 MongoDB Update Java Driver – Remove a field
- 1.16 MongoDB Update Java Driver – Insert a new document if no match found
- 1.17 MongoDB Update Java Driver – Update multiple documents
MongoDB update
MongoDB shell client update syntax is:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
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.
Other options in MongoDB update are optional but important too;
- if upsert is specified as true then update query will insert a document if there are no matches to the query, default value is false.
- if multi is specified as true then all the documents that matches the query criteria will be updated, default value is false.
- writeConcern can be used to specify write concern, if not provided default write concern will be used.
MongoDB Update Document Operators
We have many mongo update parameter operators available – most widely used are $set, $inc, $currentDate.
Name | Description |
---|---|
$inc | Increments the value of the field by the specified amount. |
$mul | Multiplies the value of the field by the specified amount. |
$rename | Renames a field. |
$setOnInsert | Sets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents. |
$set | Sets the value of a field in a document. |
$unset | Removes the specified field from a document. |
$min | Only updates the field if the specified value is less than the existing field value. |
$max | Only updates the field if the specified value is greater than the existing field value. |
$currentDate | Sets the value of a field to current date, either as a Date or a Timestamp. |
We will look into some of these in next sections.
Few important points to note with MongoDB update operations are:
- If <update> document contains update operators then it must contain only update operator expressions and only corresponding fields will be updated.
- If the <update> document contains only field:value expressions then it will replace the query matching document (except _id) and we can’t update multiple documents with this (make sense, it will have duplicate data).
- If upsert is true and no document matches the query criteria, update() inserts a single document. The update creates the new document with either:
The fields and values of the <update> parameter or the fields and values of both <query> and <update> parameters if the <update> parameter contains only update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter.
MongoDB Update Document Example
Now let’s see some of the MongoDB update example using Mongo shell.
MongoDB Update single field in a single document
> 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.> 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.
> 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.> 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.
> 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.> 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
> 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
> 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.
MongoDB update document example using Java Driver
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
package 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 document DBObject 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.
package 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 document DBObject 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.
package 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 document DBObject 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.
package 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 document DBObject 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.
package 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 document DBObject 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.
package 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 found DBObject 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.package 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 example DBObject 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.
Hi Pankaj,
Is it possible to update list of documents with different where conditions? I want to update in bulk but my where condition is different for each document.
Hi,
I am looking for help with my mongodb update query where I am using “inc” operator and the value by which a property has to be incremented is actually another property value in the same document.
Let’s say a document has 2 properties score and bonus. I want to set score value as (score – bonus)
{ score: {$inc: $bonus } }
But I am unable to do so. Can you please guide me about how to do the same in correct way?
Thanks & Regards,
Keya
Can you post an example of how to upsert a record based on multiple keys using MongoDB Driver and Spring?
Would like to know is there any limitation in executing the update() on the Mongo Documents. Limitations in the sense – Performance issue, when update is triggered (or) only some volume of records can be updated, etc.
a quick help.. how to add a new subdocument (array) to an existing document.
I have already added a document by doing this
collection.insertOne(new Document().append(“name”, “jones”));
now I need to add a subdocument movieList to this document
I have created a movielist array by doing something like this
List movieList = new ArrayList();
movieList.add(“Castlevania”);
movieList.add(“Shangai”);
when I do
collection.updateOne(Filters.eq(“name”, “jones”), Updates.set(“movies”, movieList));
I get an error
Exception in thread “main” org.bson.codecs.configuration.CodecConfigurationException: Can’t find a codec for class java.util.ArrayList.
any help ?
Add toString() method to the end of your movieList. However if you want to update each element within the list, you need to iterate over the list, and
update each nested item.
Good post and its very useful. How to update document based on particular field like may be _id or email etc.
Thanks for this great tutorial
Very thankful for this tutorial
Would be nice to see the Java driver examples working with the new 3.0+ release.
Need an example on mongodb+spring+lazy loading.