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
Delete a field and value in MongoDB?
To delete a field and its value from MongoDB documents, use the $unset operator. This operator removes the specified field from all matched documents in the collection.
Syntax
db.collection.update(
{ field: { $exists: true } },
{ $unset: { fieldName: 1 } },
{ multi: true }
)
Sample Data
Let us first create a collection with sample documents −
db.deleteFieldDemo.insertMany([
{ "FirstName": "John", "LastName": "Smith" },
{ "FirstName": "David", "LastName": "Miller" },
{ "FirstName": "Carol", "LastName": "Taylor" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cb9fb767219729fde21ddad"),
ObjectId("5cb9fb837219729fde21ddae"),
ObjectId("5cb9fb8d7219729fde21ddaf")
]
}
Display all documents from the collection −
db.deleteFieldDemo.find().pretty();
{
"_id": ObjectId("5cb9fb767219729fde21ddad"),
"FirstName": "John",
"LastName": "Smith"
}
{
"_id": ObjectId("5cb9fb837219729fde21ddae"),
"FirstName": "David",
"LastName": "Miller"
}
{
"_id": ObjectId("5cb9fb8d7219729fde21ddaf"),
"FirstName": "Carol",
"LastName": "Taylor"
}
Example: Delete FirstName Field
Remove the "FirstName" field from all documents −
db.deleteFieldDemo.updateMany(
{ FirstName: { $exists: true } },
{ $unset: { FirstName: 1 } }
);
{
"acknowledged": true,
"matchedCount": 3,
"modifiedCount": 3
}
Verify Result
Check if the FirstName field has been deleted −
db.deleteFieldDemo.find().pretty();
{ "_id": ObjectId("5cb9fb767219729fde21ddad"), "LastName": "Smith" }
{ "_id": ObjectId("5cb9fb837219729fde21ddae"), "LastName": "Miller" }
{ "_id": ObjectId("5cb9fb8d7219729fde21ddaf"), "LastName": "Taylor" }
Conclusion
The $unset operator effectively removes fields from MongoDB documents. Use updateMany() with $exists: true to delete a field from all documents that contain it.
Advertisements
