4

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.$': '' } }
);
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Possible duplicate of [Is object empty?](http://stackoverflow.com/questions/4994201/is-object-empty) – Avinash Feb 01 '16 at 10:45

2 Answers2

6

An alternative approach to remove empty objects from an array with no assumptions:

db.a.update(
    {"tradename": {}},
    { $pull: { 'tradename': {$in:[{}]} } },
    { "multi": true }
);
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
1

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 }
)
chridam
  • 100,957
  • 23
  • 236
  • 235