Is there a way to remove literally all null or empty string values from an object? We have an aggregation which creates an object with empty fields and empty objects should the value be null.
What we wish to do is remove all null properties and empty objects and recreate the object, in order to keep the data as small as possible.
e.g. in the following object, only ‘test’ and ‘more-nested-data’ should be taken into account, the rest can be removed
I tried a lot, but I think by using objectToArray that something could be done, but I have not found the solution yet. The required aggregation should need to recursively (or by defined levels) remove null properties and empty objects.
As you can see here, there is one gate object that is just empty, and can be left out. It does a great job of leaving the properties out, but the parent path is still constructed though
The same thing happens in some cases where we convert some strings to dates, should these strings be null, the value will also be null and the property stays present
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.