-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Aggregation Framework
-
Query Optimization
The $addFields pipeline stage allows us to replace a field if the field already exists. Unfortunately, the intention to replace rather than add becomes muddled for documents returned from the query that don't contain the field. The nonexistence of the field in those documents changes the effect from replace to add, even though we really just wanted to replace.
In my application, I often must return query results where nested arrays are filtered. I've found that using $addFields pipeline stages mostly accomplishes this. For each nested array that I must filter, I construct the corresponding pipeline stage as follows:
"{ $addFields: { '" + arrayFilter.field + "': { $filter: { input: '$" + arrayFilter.field + "', cond: { " + arrayFilter.cond + " } } } } }" );
But a problem arises when one of the path segments in arrayFilter.field doesn't exist in the database. The problem is compounded when arrayFilter.field is nested, i.e. contains dots.
Under those circumstances, I want the stage to have zero effect. Unfortunately, the query result is such that:
- the path leading to the nonexistent array is materialized
- the unwanted array is given a null value.
Such problems could be avoided by introducing a $replaceFields pipeline stage that we can use to unambiguously declare our intention to replace rather than add.