
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update MongoDB Document Without Overwriting Existing One
To update only a field value, use update() along with $set. This won’t overwrite the existing one. Let us first create a collection with documents −
> db.demo401.insertOne( ... { ... "_id" : 1001, ... "Name" : "Chris", ... "SubjectName" : "MongoDB", ... "Score" : 45 ... } ... ); { "acknowledged" : true, "insertedId" : 1001 }
Display all documents from a collection with the help of find() method −
> db.demo401.find();
This will produce the following output −
{ "_id" : 1001, "Name" : "Chris", "SubjectName" : "MongoDB", "Score" : 45 }
Following is the query to update a document without overwriting the existing one −
> db.demo401.update({_id: 1001}, {$set: {Score:89}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo401.find();
This will produce the following output −
{ "_id" : 1001, "Name" : "Chris", "SubjectName" : "MongoDB", "Score" : 89 }
Advertisements