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.$': '' } }
);
1
  • Possible duplicate of Is object empty? Commented Feb 1, 2016 at 10:45

2 Answers 2

6

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

db.a.update(
    {"tradename": {}},
    { $pull: { 'tradename': {$in:[{}]} } },
    { "multi": true }
);
Sign up to request clarification or add additional context in comments.

Comments

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 }
)

2 Comments

this my remove elements if that object does not have 'element' property
@Azzi That's why I said explicitly given that the embedded document has the element property only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.