Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
MongoDB query to remove empty objects in an object-array?
You can use $pull operator for this. Let us first create a collection with documents. Here, we have also added an empty object −
> db.removeEmptyObjectsDemo.insertOne(
{
"_id" :101,
"LoginDate" :new ISODate(),
"UserDetails" : [
{
"UserName" : "John"
},
{
},
{
"UserName" : "Sam"
}
]
}
);
{ "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeEmptyObjectsDemo.find().pretty();
This will produce the following output −
{
"_id" : 101,
"LoginDate" : ISODate("2019-05-25T04:46:29.505Z"),
"UserDetails" : [
{
"UserName" : "John"
},
{
},
{
"UserName" : "Sam"
}
]
}
Following is the query to remove empty objects in an object-array −
> db.removeEmptyObjectsDemo.update(
{},
{ "$pull": { "UserDetails": { "UserName": { "$exists": false } } } },
{ "multi": true }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from the above collection −
> db.removeEmptyObjectsDemo.find().pretty();
This will produce the following output. The empty object removed successfully −
{
"_id" : 101,
"LoginDate" : ISODate("2019-05-25T04:46:29.505Z"),
"UserDetails" : [
{
"UserName" : "John"
},
{
"UserName" : "Sam"
}
]
}Advertisements