Mongodb matches an empty object in a subdocument

I'm just wondering if this can be done in a single request?

Considering

{ _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 this in a few queries, but I'm trying to better understand MongoDB.


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

Is it possible to delete it with its contents? But the sender of the command does not know if there are other keys except baz at the moment.

+7
source share
1 answer

You can search for empty nested documents ( { } ) and $unset them .. here is an example in the JS shell:

 db.mycoll.update( {'foo.fred':{ }}, { $unset: {'foo.fred':1} }, false, // upsert: no true // multi: find all matches ) 
+8
source

All Articles