MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

MongoDB- Recupero dell'elemento esatto dell'array, esclusi gli altri

Questo è un malinteso standard e comprensibile sull'array di array con MongoDB. I criteri della query produrranno il risultato corretto nell'ambito di un document , non necessariamente solo gli elementi in una matrice che stai cercando. In altre parole, dato l'obiettivo desiderato di trovare DATA NOT FOUND , le query più semplici troveranno qualsiasi documento in cui almeno un elemento nell'array corrisponde, ma non filtreranno quelli che non lo fanno. Devi diventare un po' più complesso per farlo in un colpo solo:

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"] }
                    }}
            }
            }}
    }}

                       ]);