- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove null element from MongoDB array?
You can use $pull operator for this. Let us first create a collection with documents −
> db.removeNullDemo.insertOne( ... { ... "_id" : 1, ... "StudentDetails" : [ ... { ... "FirstName": "John", ... "LastName":"Smith", ... ... }, ... { ... "Age":21 ... }, ... null ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 1 } > db.removeNullDemo.insertOne( ... { ... "_id" : 2, ... "StudentDetails" : [ ... { ... "FirstName": "Carol", ... "LastName":"Taylor", ... ... }, ... { ... "Age":23 ... } ... ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 2 }
Following is the query to display all documents from the collection with the help of find() method −
> db.removeNullDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "StudentDetails" : [ { "FirstName" : "John", "LastName" : "Smith" }, { "Age" : 21 }, null ] } { "_id" : 2, "StudentDetails" : [ { "FirstName" : "Carol", "LastName" : "Taylor" }, { "Age" : 23 } ] }
Following is the query to remove null element from MongoDB array −
> db.removeNullDemo.update({_id:1},{$pull:{StudentDetails:null}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the null has been removed or not −
> db.removeNullDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "StudentDetails" : [ { "FirstName" : "John", "LastName" : "Smith" }, { "Age" : 21 } ] } { "_id" : 2, "StudentDetails" : [ { "FirstName" : "Carol", "LastName" : "Taylor" }, { "Age" : 23 } ] }
Advertisements