 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
How to update record in MongoDB without replacing the existing fields?
You can use $set operator for this Let us first create a collection with documents −
> db.updateRecordDemo.insertOne({"StudentName":"Larry"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6f95de8cc557214c0e0a") } > db.updateRecordDemo.insertOne({"StudentName":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6f9cde8cc557214c0e0b") } > db.updateRecordDemo.insertOne({"StudentName":"Mike"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6f9dde8cc557214c0e0c") } Display all documents from a collection with the help of find() method −
> db.updateRecordDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbd6f95de8cc557214c0e0a"), "StudentName" : "Larry" } { "_id" : ObjectId("5cbd6f9cde8cc557214c0e0b"), "StudentName" : "David" } { "_id" : ObjectId("5cbd6f9dde8cc557214c0e0c"), "StudentName" : "Mike" } Following is the query to update record in MongoDB without replacing the existing fields −
> db.updateRecordDemo.update({"_id" :ObjectId("5cbd6f9cde8cc557214c0e0b") },{$set : {"StudentAge":24}});    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Let us Display all documents from the collection once again −
> db.updateRecordDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbd6f95de8cc557214c0e0a"), "StudentName" : "Larry" } {    "_id" : ObjectId("5cbd6f9cde8cc557214c0e0b"),    "StudentName" : "David",    "StudentAge" : 24 } { "_id" : ObjectId("5cbd6f9dde8cc557214c0e0c"), "StudentName" : "Mike" }Advertisements
 