
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 Key Fields in MongoDB
To remove key fields in MongoFB, you can use $unset operator. Let us first create a collection with documents −
>db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6c8289cb58ca2b005e672") } >db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6c8359cb58ca2b005e673") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeKeyFieldsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 } { "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith", "StudentAge" : 21 }
Following is the query to remove key fields. Here, we are removing the StudentAge −
> db.removeKeyFieldsDemo.updateMany({},{$unset:{StudentAge:1}}); { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Let us display all documents from the above collection −
> db.removeKeyFieldsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" } { "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }
Advertisements