Dette er en standard og forståelig array-of-array misforståelse med MongoDB. Forespørgselskriterierne vil give det korrekte resultat i et dokument , ikke nødvendigvis bare elementerne i et array, du leder efter. Med andre ord, givet dit ønskede mål om at finde DATA NOT FOUND
, vil de fleste simple forespørgsler finde ethvert dokument, hvor mindst ét element i arrayet matcher -- men vil ikke bortfiltrere dem, der ikke gør det. Du skal blive lidt mere kompleks for at gøre dette på én gang:
db.foo.aggregate([
// Make sure at *least* one label has a remark of DATA NOT FOUND;
// otherwise, the $filter trick in the next stage yields a labels array
// of length 0 (which is not horrible). Also, this is a good place to
// add other $match criteria, possibly index-optimized, to shrink down the
// size of response set:
{$match: {"divisionIn.sections.labels.remarks":"DATA NOT FOUND"}}
,{$project: {
// Copy over the main doc level things we want:
projectDR: "$projectDR",
code: "$code",
status: "$status"
// divisionIn is a map, not an array, so we can dive down using dot notation
// and make a new sections array called divSections that will ONLY have
// DATA NOT FOUND:
divSections: {$map: {input: "$divisionIn.sections", as:"z", in:
{
// Again, copy over things we want to keep; may not need all of them
"sectionNumber": "$$z.sectionNumber",
"sectionName": "$$z.sectionName",
// The Juice: Copy BUT FILTER the labels field conditionally based on
// the value of labels.remarks:
"labels": {$filter: {input: "$$z.labels",
as: "z2",
cond: {$eq: [ "$$z2.remarks", "DATA NOT FOUND"] }
}}
}
}}
}}
]);