- 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
How to add a field with specific datatype (list, object) in an existing MongoDB document?
You can use $set. Let us create a collection with documents −
> db.demo732.insertOne({_id:1,Language:"English"}); { "acknowledged" : true, "insertedId" : 1 } > db.demo732.insertOne({_id:2,Language:"Hindi"}); { "acknowledged" : true, "insertedId" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo732.find();
This will produce the following output −
{ "_id" : 1, "Language" : "English" } { "_id" : 2, "Language" : "Hindi" }
Following is the query to add a field with specific datatype (list, object) in an existing MongoDB document −
> db.demo732.update({_id:1}, ... { $set:{details:{'subjectName':"MongoDB"}, studentDetails:[{Name:"David"},{CountryName:"US"}]}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo732.find();
This will produce the following output −
{ "_id" : 1, "Language" : "English", "details" : { "subjectName" : "MongoDB" }, "studentDetails" : [ { "Name" : "David" }, { "CountryName" : "US" } ] } { "_id" : 2, "Language" : "Hindi" }
Advertisements