Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
}
]
}Advertisements