So far, after i tried, i came up with solution where i am able to remove the whole object inside of the array if that object has field with empty value. That does not work in my case. I only need to remove the field and keep rest of the object. In this case, "Comment" field is the one having empty values occasionally. Thanks in advance!
Structure:
someArray: [
{
field1:"value",
field2:"value",
Comment:"",
Answer:"",
},
{
field1:"value",
field2:"value",
Comment:"",
Answer:"",
}]
Code:
$project: {
someArray: {
$filter: {
input: "$someArray", as: "array",
cond: { $ne: [ "$$array.Comment", ""]}}}}
3
Answers
Use
$map
to loop over the array elements.For each array element where comment is not an empty string, return whole element, otherwise return the document excluding comment field. Like this:Here, is the working link.
Solution from Charchit Kapoor works only if your array has exactly
But it does not work for arbitrary fields. I was looking for more generic solution, my first idea was this:
but it does not work.
I ended on this one:
Mongo Playground
Here is a solution where an array’s nested object can have multiple fields and these need not be referred in the aggregation. Removes the nested object’s field with value as an empty string (
""
):