- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" } }
- Related Articles
- How to push an element into array in MongoDB?
- MongoDB query on nth element (variable index) of subdocument array
- Push query results into variable with MongoDB?
- Cannot push into an array from MongoDB?
- MongoDB query to push document into an array
- How to access subdocument value when the key is a number in MongoDB?
- Sort by subdocument in MongoDB
- How to push new items to an array inside of an object in MongoDB?
- MongoDB to sort by subdocument match?
- Update an array element matching a condition using $push in MongoDB
- MongoDB query to update an array element matching a condition using $push?
- MongoDB query to remove subdocument from document?
- MongoDB $push in nested array?
- Work with $push in MongoDB
- How to filter array in subdocument with MongoDB?

Advertisements