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" } ] }