- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Updating a MongoDB document and adding new keys only in the first document?
This can be easily achieved using MongoDB update(). Let us create a collection with documents −
> db.demo162.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3684359e4f06af551997c2") } > db.demo162.insertOne({"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3684389e4f06af551997c3") } > db.demo162.insertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e36843c9e4f06af551997c4") }
Display all documents from a collection with the help of find() method −
> db.demo162.find();
This will produce the following output −
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 } { "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" } { "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
Here is the query to update a document, adding new keys in first document −
> db.demo162.update({},{$set:{"StudentAge":23}},{upsert:true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo162.find();
This will produce the following output −
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 } { "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" } { "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
- Related Articles
- Updating nested document in MongoDB
- Adding new property to each document in a large MongoDB collection?
- How to update a MongoDB document for adding a new item to an array?
- Update only a single document in MongoDB
- Remove only a single document in MongoDB
- Conditional upsert (multiple insert) when updating document in MongoDB?
- Retrieving the first document in a MongoDB collection?
- Remove only one document in MongoDB?
- How to use custom variable while updating a MongoDB document?
- How to count number of keys in a MongoDB document?
- Increment only a single value in MongoDB document?
- Update only a specific value in a MongoDB document
- MongoDB syntax for updating an object inside an array within a document?
- MongoDB query to return only embedded document?
- Retrieve only a single document specifying a criteria in MongoDB?

Advertisements