- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does MongoDB Update() method work to set records of entire field?
You can use $set operator along with update(). Let us first create a collection with documents −
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd506fe2cba06f46efe9efa") } > db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efb") } > db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efc") } > db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd507032cba06f46efe9efd") }
Following is the query to display all documents from a collection with the help of find() method −
> db.workingOfUpdateMethod.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "AUS" } { "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "AUS" } { "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "AUS" } { "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "AUS" }
Following is the query to update and set an entire field. Here, we are updating the field “ClientCountryName” −
> db.workingOfUpdateMethod.update( ... {"ClientCountryName" : "AUS"}, ... {$set: {"ClientCountryName" : "UK"}}, ... {multi: true}); WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
Let us check the all the documents once again −
> db.workingOfUpdateMethod.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "UK" } { "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "UK" } { "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "UK" } { "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "UK" }
Advertisements