17

I'm just wondering if this is possible to do in a single request?

Given

{
   _id: 1,
   foo: {
     fred: {},          // <- I want to remove empty keys like this
     barney: { bar: 1 } // <- But keep these keys
   }
}

Expected

{
   _id: 1,
   foo: {
     barney: { bar: 1 }
   }
}

I know how to do it in several requests, but I'm trying to understand MongoDB better.


Note. fred becomes empty in update command like { $unset: { "fred.baz": 1 } } when baz is the last key in fred.

Maybe it is possible to remove it with its contents? But the command sender does not know, is there any other keys, except baz at the moment.

1 Answer 1

24

You can search for empty embedded docs ({ }) and $unset them .. here's an example in the JS shell:

db.mycoll.update(
    {'foo.fred':{ }},
    { $unset: {'foo.fred':1} },
    false,  // upsert: no
    true    // multi: find all matches
)
Sign up to request clarification or add additional context in comments.

2 Comments

How would you write is not { } meaning has fields in object ?
With query {'foo.fred':{ '$gt' : {} }} you would receive documents with non empty foo.fred attribute.

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.