
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
Push New Key Element into Subdocument of MongoDB
You can use $set operator for this. Following is the syntax −
db.yourCollectionName.update({"_id" : yourObjectId },{$set: { "yourOuterFieldName.anyInnerFieldName": yourValue}});
Let us first create a collection with documents −
> db.pushNewKeyDemo.insertOne({"UserId":100,"UserDetails":{}}); { "acknowledged" : true, "insertedId" : ObjectId("5cda58f5b50a6c6dd317adbf") }
Following is the query to display all documents from a collection with the help of find() method −
> db.pushNewKeyDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { } }
Following is the query to push new key element into subdocument of MongoDB −
> db.pushNewKeyDemo.update({"_id" : ObjectId("5cda58f5b50a6c6dd317adbf")},{$set: { "UserDetails.UserName": "David Miller"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.pushNewKeyDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { "UserName" : "David Miller" } }
Advertisements