Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove key fields in MongoDB?
To remove key fields in MongoDB, you can use the $unset operator. This operator deletes specified fields from documents in a collection.
Syntax
db.collection.updateMany(
{ query },
{ $unset: { fieldName: 1 } }
);
Sample Data
Let us first create a collection with sample documents ?
db.removeKeyFieldsDemo.insertMany([
{
"StudentFirstName": "John",
"StudentLastName": "Doe",
"StudentAge": 23
},
{
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentAge": 21
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc6c8289cb58ca2b005e672"),
ObjectId("5cc6c8359cb58ca2b005e673")
]
}
View Sample Data
db.removeKeyFieldsDemo.find();
{
"_id": ObjectId("5cc6c8289cb58ca2b005e672"),
"StudentFirstName": "John",
"StudentLastName": "Doe",
"StudentAge": 23
}
{
"_id": ObjectId("5cc6c8359cb58ca2b005e673"),
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentAge": 21
}
Remove Key Fields
Now let's remove the StudentAge field from all documents ?
db.removeKeyFieldsDemo.updateMany(
{},
{ $unset: { StudentAge: 1 } }
);
{
"acknowledged": true,
"matchedCount": 2,
"modifiedCount": 2
}
Verify Result
db.removeKeyFieldsDemo.find();
{
"_id": ObjectId("5cc6c8289cb58ca2b005e672"),
"StudentFirstName": "John",
"StudentLastName": "Doe"
}
{
"_id": ObjectId("5cc6c8359cb58ca2b005e673"),
"StudentFirstName": "John",
"StudentLastName": "Smith"
}
Key Points
- The value
1in$unsetis just a placeholder; any value works. - Use an empty query
{}to remove fields from all documents. - Add specific conditions to target only certain documents.
Conclusion
The $unset operator efficiently removes unwanted fields from MongoDB documents. Combine it with updateMany() to remove fields from multiple documents at once.
Advertisements
