sql >> Base de Datos >  >> NoSQL >> MongoDB

MongoDB- Obtener el elemento de matriz exacto, excluyendo otros

Este es un concepto erróneo estándar y comprensible de matriz de matriz con MongoDB. Los criterios de consulta arrojarán el resultado adecuado en el ámbito de un documento , no necesariamente solo los elementos de una matriz que está buscando. En otras palabras, dado su objetivo deseado de encontrar DATA NOT FOUND , la mayoría de las consultas simples encontrarán cualquier documento en el que coincida al menos un elemento de la matriz, pero no filtrará aquellos que no coincidan. Tienes que ser un poco más complejo para hacer esto de una sola vez:

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

                       ]);