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
MongoDB query to remove empty objects in an object-array?
To remove empty objects from an object-array in MongoDB, use the $pull operator combined with $exists: false to match objects that lack any fields. This effectively removes objects with no key-value pairs.
Syntax
db.collection.update(
{},
{ "$pull": { "arrayField": { "fieldName": { "$exists": false } } } },
{ "multi": true }
);
Sample Data
Let us create a collection with documents containing empty objects in the array ?
db.removeEmptyObjectsDemo.insertOne({
"_id": 101,
"LoginDate": new ISODate(),
"UserDetails": [
{
"UserName": "John"
},
{
},
{
"UserName": "Sam"
}
]
});
{ "acknowledged": true, "insertedId": 101 }
Display the document to verify the data structure ?
db.removeEmptyObjectsDemo.find().pretty();
{
"_id": 101,
"LoginDate": ISODate("2019-05-25T04:46:29.505Z"),
"UserDetails": [
{
"UserName": "John"
},
{
},
{
"UserName": "Sam"
}
]
}
Remove Empty Objects
Use $pull with $exists: false to remove objects that don't contain the specified field ?
db.removeEmptyObjectsDemo.update(
{},
{ "$pull": { "UserDetails": { "UserName": { "$exists": false } } } },
{ "multi": true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check the updated document to confirm empty objects are removed ?
db.removeEmptyObjectsDemo.find().pretty();
{
"_id": 101,
"LoginDate": ISODate("2019-05-25T04:46:29.505Z"),
"UserDetails": [
{
"UserName": "John"
},
{
"UserName": "Sam"
}
]
}
Conclusion
The $pull operator with $exists: false effectively removes empty objects from arrays by targeting objects that lack specific fields. Use multi: true to update all matching documents in the collection.
Advertisements
