- 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
Unset an attribute from a single array element in MongoDB?
Use $unset operator to unset an attribute. Let us first create a collection with documents −
> db.unsetAnAttributeDemo.insertOne( ... { ... _id: 1, ... "StudentDetails": [ ... { ... "StudentFirstName": "Ramit", ... "StudentCountryName":"UK" ... }, ... { ... "StudentFirstName": "Bob", ... "StudentCountryName":"US" ... }, ... { ... "StudentFirstName": "Carol", ... "StudentCountryName":"AUS" ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from the collection with the help of find() method −
> db.unsetAnAttributeDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "StudentDetails" : [ { "StudentFirstName" : "Ramit", "StudentCountryName" : "UK" }, { "StudentFirstName" : "Bob", "StudentCountryName" : "US" }, { "StudentFirstName" : "Carol", "StudentCountryName" : "AUS" } ] }
Following is the query to unset an attribute from a single array element. The attribute “StudentCountryName” with value “AUS” will unset −
> db.unsetAnAttributeDemo.update({"StudentDetails.StudentCountryName": "AUS"}, {$unset: {"StudentDetails.$.StudentCountryName": 1}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the document from the collection to check that attribute StudentCountryName with value “AUS” has been cleared or not −
> db.unsetAnAttributeDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "StudentDetails" : [ { "StudentFirstName" : "Ramit", "StudentCountryName" : "UK" }, { "StudentFirstName" : "Bob", "StudentCountryName" : "US" }, { "StudentFirstName" : "Carol" } ] }
Advertisements