- 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
Using findOneAndUpdate () to update in MongoDB?
The findOneAndUpdate() is used to update a single document based on the filter and sort criteria i.e. −
db.collection.findOneAndUpdate(filter, update, options)
Let us create a collection with documents −
> db.demo328.insertOne({Name:"Chris",Marks:67}); { "acknowledged" : true, "insertedId" : ObjectId("5e516b19f8647eb59e56207a") } > db.demo328.insertOne({Name:"David",Marks:78}); { "acknowledged" : true, "insertedId" : ObjectId("5e516b24f8647eb59e56207b") } > db.demo328.insertOne({Name:"Bob",Marks:97}); { "acknowledged" : true, "insertedId" : ObjectId("5e516b2bf8647eb59e56207c") }
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 } { "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 } { "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
Following is the query to update with findOneAndUpdate(). Here, we are incrementing a specific document’s field Marks −
> db.demo328.findOneAndUpdate({Name:"David"},{ $inc: { "Marks" : 10} }); { "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 }
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 } { "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 88 } { "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
Advertisements