Aggregation for match in array return full object

I have a data that I would like to filter to return this full object but with only the matches of productTypeCode. Eg. my list has [“22202”, “22208”], it should return custid, products with 2 element. I tried with aggregation but it still returns all 3 elements, would appreciate if you can point my mistakes, thanks.
{
“custid”: {
“cpid”: “412412”,
},
“products”: [
{
“productRef”: {
“number”: “00312350”,
},
“productType”: null,
“productTypeCode”: “22202”,
},
{
“productRef”: {
“number”: “0120083”,
},
“productType”: null,
“productTypeCode”: “22208”,
},
{
“productRef”: {
“number”: “02420032”,
},
“productType”: null,
“productTypeCode”: “22207”,
}
],
“services”: []
}

@Aggregation(pipeline = {
“{’$match’:{‘custId.cpid’: ?0 }}”,
“{ ‘$filter’: { input: ‘products’, as: ‘prod’, cond: {‘products.productTypeCode’ : {$in: ?1}} } }”
})
Mono findByProductCodeList(String cmcpid, List prodTypeCode);

$filter is not a stage.

you need a $set, $addFields or $project stage.

you then you $filter inside.

verify your $filter syntax, you define as:prod but use products.productTypeCode.

1 Like

your “$filter” needs to reside in a “$project” as described in $filter (aggregation) — MongoDB Manual

and “$in” must be of the form “{ $in: [ field, array] }” instead of “{ field: { $in : array } }” as in $in (aggregation) — MongoDB Manual

also field name “cond” must match the name in “as” with double dollar signs “$$prod.productType”

you can also omit the " as:‘prod’ " and use " $$this.productType " to refer current element of filtered array.