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
Removing an object in a child collection in MongoDB?
To remove an object in a child collection, use $pull in MongoDB. Let us create a collection with documents −
> db.demo715.insertOne({
... _id:1,
... details :
... [
... { 'id' : '101',
... 'Information' : [
... {
... 'studentid' : '102',
... "Name":"Bob"
... },
... {
... 'studentid' : '103',
... "Name":"Chris"
... }
... ]
... }
... ]
... });
{ "acknowledged" : true, "insertedId" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo715.find();
This will produce the following output −
{ "_id" : 1, "details" : [ { "id" : "101", "Information" : [ { "studentid" : "102", "Name" : "Bob" }, { "studentid" : "103", "Name" : "Chris" } ] } ] }
Following is the query to remove an object in a child collection in MongoDB −
> db.demo715.update(
... {"details.id":'101'},
... { $pull: { 'details.$.Information':{studentid:'102',"Name":"Bob"} } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo715.find();
This will produce the following output −
{ "_id" : 1, "details" : [ { "id" : "101", "Information" : [ { "studentid" : "103", "Name" : "Chris" } ] } ] }Advertisements