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.
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With