
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" }
- Related Questions & Answers
- Remove and update the existing record in MongoDB?
- How to update a MongoDB document without overwriting the existing one?
- MongoDB query to update selected fields
- Update only specific fields in MongoDB?
- How can we update a record in MongoDB?
- Include all existing fields and add new fields to document in MongoDB?
- MongoDB query to update only certain fields?
- How do I add a field to existing record in MongoDB?
- How do you update a MongoDB document while replacing the entire document?
- How to update an existing document in MongoDB collection using Java?
- How to update or modify the existing documents of a collection in MongoDB?
- How to exclude _id without including other fields using the aggregation framework in MongoDB?
- What is the fastest way to update the whole document (all fields) in MongoDB?
- How can I update and increment two fields in one command in MongoDB?
- How to update existing data in EEPROM with Arduino?
Advertisements