Pavel Koryagin
Pavel Koryagin

Reputation: 1481

Mongodb match empty object in nested document

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.

Upvotes: 16

Views: 17552

Answers (1)

Stennie
Stennie

Reputation: 65323

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
)

Upvotes: 22

Related Questions