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
Removing empty fields from MongoDB
To remove empty fields from MongoDB documents, use updateMany() with the $unset operator. This operation identifies documents with empty string values and removes those fields entirely.
Syntax
db.collection.updateMany(
{ "fieldName": "" },
{ $unset: { "fieldName": 1 } }
);
Sample Data
Let us create a collection with documents containing empty fields ?
db.removeEmptyFieldsDemo.insertMany([
{ "StudentName": "" },
{ "StudentName": "Chris" },
{ "StudentName": "" },
{ "StudentName": "Robert" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ce92b9578f00858fb12e919"),
ObjectId("5ce92b9878f00858fb12e91a"),
ObjectId("5ce92b9c78f00858fb12e91b"),
ObjectId("5ce92ba078f00858fb12e91c")
]
}
View Current Documents
db.removeEmptyFieldsDemo.find();
{ "_id": ObjectId("5ce92b9578f00858fb12e919"), "StudentName": "" }
{ "_id": ObjectId("5ce92b9878f00858fb12e91a"), "StudentName": "Chris" }
{ "_id": ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName": "" }
{ "_id": ObjectId("5ce92ba078f00858fb12e91c"), "StudentName": "Robert" }
Remove Empty Fields
Use updateMany() to remove all empty StudentName fields ?
db.removeEmptyFieldsDemo.updateMany(
{ "StudentName": "" },
{ $unset: { "StudentName": 1 } }
);
{ "acknowledged": true, "matchedCount": 2, "modifiedCount": 2 }
Verify Results
db.removeEmptyFieldsDemo.find();
{ "_id": ObjectId("5ce92b9578f00858fb12e919") }
{ "_id": ObjectId("5ce92b9878f00858fb12e91a"), "StudentName": "Chris" }
{ "_id": ObjectId("5ce92b9c78f00858fb12e91b") }
{ "_id": ObjectId("5ce92ba078f00858fb12e91c"), "StudentName": "Robert" }
Conclusion
The $unset operator with updateMany() effectively removes empty string fields from MongoDB documents. Documents with empty fields will have those fields completely removed, while documents with valid values remain unchanged.
Advertisements
