
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" } ] }
- Related Questions & Answers
- Removing an array element from a MongoDB collection
- PHP program to delete an element from the array using the unset function
- Get a single element from the array of results by index in MongoDB
- How to delete element from an array in MongoDB?
- Remove null element from MongoDB array?
- MongoDB query to match and remove element from an array?
- How to remove an element from a doubly-nested array in a MongoDB document?
- Extract a particular element from a nested array in MongoDB
- How to unset a variable in MongoDB shell?
- How to unset objects in MongoDB?
- How to get a particular element from MongoDB array?
- MongoDB query to pull array element from a collection?
- Removing an array element from MongoDB collection using update() and $pull
- How to remove a specific element from array in MongoDB?
- Aggregate a $slice to get an element in exact position from a nested array in MongoDB?
Advertisements