- 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
Updating sub-object in MongoDB?
You can use $set operator for this. Let us first create a collection with documents −
> db.updateSubObjectDemo.insertOne( ... { ... ... "ClientId" : 100, ... "ClientDetails" : { ... "ClientFirstName" : "Adam" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd31434b64f4b851c3a13e9") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updateSubObjectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd31434b64f4b851c3a13e9"), "ClientId" : 100, "ClientDetails" : { "ClientFirstName" : "Adam" } }
Following is the query to update sub-object in MongoDB. Here, we have set ClientLastName −
> db.updateSubObjectDemo.update({ClientId : 100}, { $set : { "ClientDetails.ClientLastName" : "Smith"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display all documents from the above collection −
> db.updateSubObjectDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd31434b64f4b851c3a13e9"), "ClientId" : 100, "ClientDetails" : { "ClientFirstName" : "Adam", "ClientLastName" : "Smith" } }
- Related Articles
- Updating data in MongoDB
- Updating nested document in MongoDB
- MongoDB syntax for updating an object inside an array within a document?
- Updating Nested Embedded Documents in MongoDB?
- Updating MongoDB collection for _id?
- Filter sub documents by sub document in MongoDB?
- Updating an array with $push in MongoDB
- Pull an element in sub of sub-array in MongoDB?
- Updating copied object also updates the parent object in JavaScript?
- Update objects in a MongoDB documents array (nested updating)?
- Conditional upsert (multiple insert) when updating document in MongoDB?
- MongoDB query by sub-field?
- Sum MongoDB Sub-documents field?
- MongoDB filter multiple sub-documents?
- How to add a sub-document to sub-document array in MongoDB?

Advertisements