- 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
Fastest way of updating in MongoDB is update() or save()?
The fastest way of updating is update(). Let us create a collection with documents and see how update() works −
> db.demo320.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ee51f8647eb59e562066") } > db.demo320.insertOne({"Name":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ee55f8647eb59e562067") } > db.demo320.insertOne({"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ee59f8647eb59e562068") } > db.demo320.insertOne({"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ee5bf8647eb59e562069") }
Display all documents from a collection with the help of find() method −
> db.demo320.find();
This will produce the following output −
{ "_id" : ObjectId("5e50ee51f8647eb59e562066"), "Name" : "Chris" } { "_id" : ObjectId("5e50ee55f8647eb59e562067"), "Name" : "Robert" } { "_id" : ObjectId("5e50ee59f8647eb59e562068"), "Name" : "Mike" } { "_id" : ObjectId("5e50ee5bf8647eb59e562069"), "Name" : "Sam" }
Following is the query to update() −
> db.demo320.update({Name:"Mike"},{$set:{Name:"Bob"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo320.find();
This will produce the following output −
{ "_id" : ObjectId("5e50ee51f8647eb59e562066"), "Name" : "Chris" } { "_id" : ObjectId("5e50ee55f8647eb59e562067"), "Name" : "Robert" } { "_id" : ObjectId("5e50ee59f8647eb59e562068"), "Name" : "Bob" } { "_id" : ObjectId("5e50ee5bf8647eb59e562069"), "Name" : "Sam" }
Advertisements