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
Remove null element from MongoDB array?
To remove null elements from a MongoDB array, use the $pull operator. This operator removes all instances of specified values from an array field, making it perfect for eliminating null entries.
Syntax
db.collection.update(
{ /* query criteria */ },
{ $pull: { "arrayField": null } }
);
Sample Data
Let us create a collection with documents containing null values in arrays ?
db.removeNullDemo.insertMany([
{
"_id": 1,
"StudentDetails": [
{
"FirstName": "John",
"LastName": "Smith"
},
{
"Age": 21
},
null
]
},
{
"_id": 2,
"StudentDetails": [
{
"FirstName": "Carol",
"LastName": "Taylor"
},
{
"Age": 23
}
]
}
]);
{ "acknowledged": true, "insertedIds": [1, 2] }
Display Current Data
db.removeNullDemo.find().pretty();
{
"_id": 1,
"StudentDetails": [
{
"FirstName": "John",
"LastName": "Smith"
},
{
"Age": 21
},
null
]
}
{
"_id": 2,
"StudentDetails": [
{
"FirstName": "Carol",
"LastName": "Taylor"
},
{
"Age": 23
}
]
}
Remove Null Elements
Use $pull to remove null values from the StudentDetails array ?
db.removeNullDemo.update(
{ _id: 1 },
{ $pull: { StudentDetails: null } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.removeNullDemo.find().pretty();
{
"_id": 1,
"StudentDetails": [
{
"FirstName": "John",
"LastName": "Smith"
},
{
"Age": 21
}
]
}
{
"_id": 2,
"StudentDetails": [
{
"FirstName": "Carol",
"LastName": "Taylor"
},
{
"Age": 23
}
]
}
Remove Null from All Documents
To remove null values from all documents in the collection, use an empty query filter ?
db.removeNullDemo.updateMany(
{},
{ $pull: { StudentDetails: null } }
);
Conclusion
The $pull operator effectively removes null elements from MongoDB arrays. Use update() for single documents or updateMany() to clean null values across multiple documents in one operation.
Advertisements
