It’s easy to do what you describe at the top level of the document. It’s a little harder to do it within subdocuments, especially if you don’t know how many levels they may be embedded and/or if some of them might be array of subdocuments.
Note that you can update the documents in place, or you can use the same pipeline in aggregation without modifying original documents.
For top level fields:
db.empty.aggregate([
{$replaceWith:{
$arrayToObject:{
$filter:{
input:{$objectToArray:"$$ROOT"},
cond:{$not:{$in:["$$this.v", [null, "", {}] ]}}
}
}
}}
])
Same thing as an update:
db.empty.update(
{},
[{$replaceWith:{$arrayToObject:{$filter:{
input:{$objectToArray:"$$ROOT"},
cond:{$not:{$in:["$$this.v", [null, "", {}] ]}}
}}}}],
{multi:true}
)
It’s a little tricker to do it for subdocuments, but possible using the same approach.
Asya