- 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
Delete specific record from an array nested within another array in MongoDB?
To delete specific record, use $pull operator. Let us first create a collection with documents −
> dbdeletingSpecificRecordDemoinsertOne( { "StudentDetails": [ { "StudentName": "John", "StudentSubjectDetails": [ { "Subject": "MongoDB", "Marks":45 }, { "Subject": "MySQL", "Marks":67 } ] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cf2210ab64a577be5a2bc06") }
Following is the query to display all documents from a collection with the help of find() method −
> dbdeletingSpecificRecordDemofind()pretty();
This will produce the following document −
{ "_id" : ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetails" : [ { "StudentName" : "John", "StudentSubjectDetails" : [ { "Subject" : "MongoDB", "Marks" : 45 }, { "Subject" : "MySQL", "Marks" : 67 } ] } ] }
Here is the query to delete specific record from an array nested within another array −
> dbdeletingSpecificRecordDemoupdate({"_id": ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetailsStudentName" : "John"}, { "$pull": {"StudentDetails$StudentSubjectDetails" : { "Marks":45 }} }, multi=true ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> dbdeletingSpecificRecordDemofind()pretty();
This will produce the following document −
{ "_id" : ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetails" : [ { "StudentName" : "John", "StudentSubjectDetails" : [ { "Subject" : "MySQL", "Marks" : 67 } ] } ] }
Advertisements
To Continue Learning Please Login
Login with Google