- 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
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" }
Advertisements