- 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 an extra field in a sub document in MongoDB?
You can use update(). Let us first create a collection with documents −
> db.addExtraFieldDemo.insertOne( { "_id": 1, "UserName": "Larry" , "UserOtherDetails":[ { "UserCountryName": "US", "UserAge":23 }, { "UserCountryName": "UK", "UserAge":24 } ] } ); { "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.addExtraFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "UserName" : "Larry", "UserOtherDetails" : [ { "UserCountryName" : "US", "UserAge" : 23 }, { "UserCountryName" : "UK", "UserAge" : 24 } ] }
Following is the query to add an extra field in a sub document in MongoDB −
> db.addExtraFieldDemo.update({ "_id":1},{ "$set":{ "UserOtherDetails.0.isMarried_" : true }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents once again −
> db.addExtraFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "UserName" : "Larry", "UserOtherDetails" : [ { "UserCountryName" : "US", "UserAge" : 23, "isMarried_" : true }, { "UserCountryName" : "UK", "UserAge" : 24 } ] }
Advertisements