Reputation: 17332
Unfortunately I got some false objects in an array in some documents, which are structured like this:
{
"_id" : "8vJY4baMbdYkgHian",
"title" : "Cars",
"tradename" : [
{
},
{
"element" : "Audi"
},
{
"element" : "Mercedes"
}
]
}
As you can see in this example, the first object in the array is empty. How can I remove empty objects in all tradename
-arrays of all documents in the collection?
Collection.update(
{ 'tradename': {} },
{ $pull: { 'tradename.$': '' } }
);
Upvotes: 4
Views: 6814
Reputation: 37048
An alternative approach to remove empty objects from an array with no assumptions:
db.a.update(
{"tradename": {}},
{ $pull: { 'tradename': {$in:[{}]} } },
{ "multi": true }
);
Upvotes: 6
Reputation: 103365
The following update operation using $pull
updates all documents in the collection to remove empty objects from the array tradename
, given that the embedded document has the element
property only:
db.collection.update(
{ },
{ "$pull": { "tradename": { "element": { "$exists": false } } } },
{ "multi": true }
)
Upvotes: 1