Find with arrayFilters using Mongoose Find with arrayFilters using Mongoose mongoose mongoose

Find with arrayFilters using Mongoose


You need $filter to process inspection_data. Things are getting complicated since you have multiple levels of nestings, so before you can apply $in condition you need to get an array of all statuses for single inspection_data. To achieve that you can use direct path like "$$data.locationAspects.comments.status" but it returns an array of arrays like this:

[ [ "C" ], [ "P" ] ], [ [ "P" ] ] ]

So you have to flatten that array and that can be achieved using $reduce and $concatArrays. Try:

db.col.aggregate([    { $match: { projectID: ObjectId("00000000e614c33390237ce3") } },    {        $project: {            filtered_inspection_data: {                $filter: {                    input: "$inspection_data",                    as: "data",                    cond: {                         $let: {                            vars: {                                statuses: {                                    $reduce: {                                         input: "$$data.locationAspects.comments.status",                                         initialValue: [],                                         in: { $concatArrays: [ "$$this", "$$value" ] }                                     }                                 }                            },                            in: { $in: [ "C", "$$statuses" ] }                        }                    }                }            }        }    }])

EDIT: to match "C" or "P" you can use replace { $in: [ "C", "$$statuses" ] } with following line

{ $or: [ { $in: [ "C", "$$statuses" ] }, { $in: [ "P", "$$statuses" ] } ] }