
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
MongoDB Concurrent Update with Sub-Collection
For update, simply use update(). Use the $push operator to append a specified value and the dot notation to reach the sub collection and update inside update().
Let us create a collection with documents −
> db.demo547.insertOne( ... { ... Name : "Chris", ... Test : ... { ... "FirstTest" : ... { ... Scores: [56,29,76] ... }, ... "SecondTest" : ... { ... Scores: [98,91,78] ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8e2d579e5f92834d7f05dd") }
Display all documents from a collection with the help of find() method −
> db.demo547.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : { "Scores" : [ 56, 29, 76 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }
Following is the query for concurrent update with subcollection −
> db.demo547.update({"Name":"Chris"}, { $push:{ "Test.FirstTest.Scores" : 99}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo547.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : { "Scores" : [ 56, 29, 76, 99 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }
Advertisements