开发者

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 i开发者_开发百科t 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜