
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
Remove and Update Existing Record in MongoDB
You can use only $pull operator that removes and updates the existing record in MongoDB. Let us first create a collection with documents −
> db.removeDemo.insertOne( ... { ... "UserName" : "Larry", ... "UserDetails" : [ ... { ... "_id" : 101, ... "UserEmailId" : "[email protected]", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446") } > db.removeDemo.insertOne( ... { ... "UserName" : "Mike", ... "UserDetails" : [ ... { ... "_id" : 102, ... "UserEmailId" : "[email protected]", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "[email protected]" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ { "_id" : 102, "UserEmailId" : "[email protected]" } ] }
Let us now implement the $pull query to remove and update the existing record −
> db.removeDemo.update( ... {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")}, ... { "$pull": { "UserDetails": {"_id": 102}}} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents from the collection in order to check the objects have been removed or not −
> db.removeDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "[email protected]" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ ] }
Advertisements