- 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
How to delete particular data in a document in MongoDB?
You can use $unset. Let us first create a collection with documents −
> db.demo20.insertOne( ... { ... ... "ListOfEmployee" : [ ... { ... "EmployeeName1" : "John" ... }, ... { ... "EmployeeName2" : "Carol" ... } ... ], ... "EmployeeName2" : [] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e138c3555d0fc6657d21f12") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo20.find();
This will produce the following output −
{ "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ], "EmployeeName2" : [ ] }
Following is the query to delete particular data in a document −
> db.demo20.update({ "EmployeeName2": { "$exists": 1 }},{ "$unset": { "EmployeeName2": "" } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.demo20.find();
This will produce the following output −
{ "_id" : ObjectId("5e138c3555d0fc6657d21f12"), "ListOfEmployee" : [ { "EmployeeName1" : "John" }, { "EmployeeName2" : "Carol" } ] }
Advertisements