

- 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
Removing empty fields from MongoDB
To remove empty fields, use deleteMany(). Let us first create a collection with documents −
> db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9578f00858fb12e919") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9878f00858fb12e91a") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92b9c78f00858fb12e91b") } > db.removeEmptyFieldsDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce92ba078f00858fb12e91c") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeEmptyFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce92b9578f00858fb12e919"), "StudentName" : "" } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b"), "StudentName" : "" } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
Following is the query to remove empty fields from MongoDB −
> db.removeEmptyFieldsDemo.updateMany({"StudentName": ""}, { $unset : {"StudentName" : 1 }}); { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Let us check the document once again −
> db.removeEmptyFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce92b9578f00858fb12e919") } { "_id" : ObjectId("5ce92b9878f00858fb12e91a"), "StudentName" : "Chris" } { "_id" : ObjectId("5ce92b9c78f00858fb12e91b") } { "_id" : ObjectId("5ce92ba078f00858fb12e91c"), "StudentName" : "Robert" }
- Related Questions & Answers
- Removing item from array in MongoDB?
- Removing all the empty indices from array in JavaScript
- Retrieving a Subset of Fields from MongoDB
- Removing empty array elements in PHP
- Removing an array element from a MongoDB collection
- MongoDB query to return specific fields from an array?
- How to retrieve all nested fields from MongoDB collection?
- Concatenate fields in MongoDB?
- Removing duplicates and inserting empty strings in JavaScript
- Removing an array element from MongoDB collection using update() and $pull
- Concatenate strings from two fields into a third field in MongoDB?
- MySQL group_concat to add a separator for empty fields?
- Update only specific fields in MongoDB?
- MongoDB order by two fields sum?
- Merge two array fields in MongoDB?
Advertisements