

- 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
Add a field to an embedded document in an array in MongoDB?
You can use update() along with $ operator for this. Let us first create a collection with documents −
> db.addAFieldDemo.insertOne( ... { ... ... "ClientName" : "Larry", ... "ClientCountryName" : "US", ... "ClientOtherDetails" : [ ... { ... "ClientProjectName":"Online Banking System" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd44bdc2cba06f46efe9ee8") }
Following is the query to display all documents from a collection with the help of find() method −
> db.addAFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"), "ClientName" : "Larry", "ClientCountryName" : "US", "ClientOtherDetails" : [ { "ClientProjectName" : "Online Banking System" } ] }
Following is the query to add a field to an embedded document in an array −
> db.addAFieldDemo.update({ClientOtherDetails:{$elemMatch:{"ClientProjectName" : "Online Banking System"}}}, ... {$set :{'ClientOtherDetails.$.isMarried':true}},true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display all the documents from the above collection −
> db.addAFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"), "ClientName" : "Larry", "ClientCountryName" : "US", "ClientOtherDetails" : [ { "ClientProjectName" : "Online Banking System", "isMarried" : true } ] }
- Related Questions & Answers
- How to add an extra field in a sub document in MongoDB?
- Increment a field in MongoDB document which is embedded?
- Implement MongoDB $push in embedded document array?
- How to add a field with specific datatype (list, object) in an existing MongoDB document?
- Add new field to every document in a MongoDB collection?
- Retrieving an embedded object as a document via the aggregation framework in MongoDB?
- MongoDB query to add a document in an already created collection
- Return specific MongoDB embedded document
- How to get embedded data in a MongoDB document?
- How to add a sub-document to sub-document array in MongoDB?
- Filter query on array of embedded document with MongoDB?
- MongoDB query for fields in embedded document?
- MongoDB query to push document into an array
- MongoDB query to return only embedded document?
- MongoDB syntax for updating an object inside an array within a document?
Advertisements