Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb match empty object in nested document

Tags:

mongodb

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.

like image 381
Pavel Koryagin Avatar asked Sep 29 '11 12:09

Pavel Koryagin


People also ask

How do you match a nested field in MongoDB?

Match an Embedded/Nested Document To specify an equality condition on a field that is an embedded/nested document, use the query filter document { <field>: <value> } where <value> is the document to match.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

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
)
like image 144
Stennie Avatar answered Sep 19 '22 19:09

Stennie