Aggregation: Multi-level filters within $addField

If do not know but you probably can do it in a single $addField but it would be easier to do it in different stages.

The first $addField will filter out customer_orders with active:true like you do now.

Then a second $addField will $map customer_orders applying the $filter on the inner items.

Use at your own risk:

top_filter = { "$addFields" : {
    "value.customer_orders": { "$filter" : {
        input: "$value.customer_orders",
        as: "customer_order",
        cond: { $eq: ["$$customer_order.active", true] }
    } }
} }

inner_filter = { $addFields : {
    "value.customer_orders" : { $map : {
        input: "$value.customer_orders",
        as: "customer_order",
        in: { $mergeObjects : [
            "$$customer_order" ,
            { "items" : { "$filter" : {
                input: "$$customer_order.items",
                as: "item",
                cond: {  $eq: ["$$item.active", true]  }
            } } }
        ] } 
    } }
} }
3 Likes