- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Manipulating subdocuments in MongoDB
To manipulate subdocuments, use dot(.) notation in MongoDB. Let us first create a collection with documents −
> db.demo378.insertOne( ... { ... Name: 'Chris', ... details:[ ... {id:101,Score:56}, ... {id:102,Score:78} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a758a2ae06a1609a00b0f") }
Display all documents from a collection with the help of find() method −
> db.demo378.find();
This will produce the following output −
{ "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"), "Name" : "Chris", "details" : [ { "id" : 101, "Score" : 56 }, { "id" : 102, "Score" : 78 } ] }
Following is the query to manipulate subdocuments −
> db.demo378.update({Name: "Chris", "details.id":102 }, { $inc: { "details.$.Score": -8 } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo378.find();
This will produce the following output −
{ "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"), "Name" : "Chris", "details" : [ { "id" : 101, "Score" : 56 }, { "id" : 102, "Score" : 70 } ] }
Advertisements