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

¿Es posible agrupar y sumar varias columnas con el marco de agregación de MongoDB?

Desde MongoDB 3.4, esto se puede lograr de manera un poco más simple usando múltiples canalizaciones de agregación con $facet .

tomado de los docs :

Entonces, para su caso de uso, esto se lograría de la siguiente manera:

const aggregatorOpts = [
    { $match: { character: 'broquaint' } }, // Match the character
    {
        // Seperate into 2 or more pipes that will count class and
        // race seperatly
        $facet: {
            race: [
                // Group by race and get the count:
                // [
                //   {
                //     _id: 'Halfling',
                //     count: 3
                //   }
                //   {
                //     _id: 'Naga',
                //     count: 2
                //   }
                // ]

                // $sortByCount is the same as
                // { $group: { _id: <expression>, count: { $sum: 1 } } },
                // { $sort: { count: -1 } }

                { $sortByCount: '$race' },

                // Now we want to transform the array in to 1 document,
                // where the '_id' field is the key, and the 'count' is the value.
                // To achieve this we will use $arrayToObject. According the the
                // docs, we have to first rename the fields to 'k' for the key,
                // and 'v' for the value. We use $project for this:
                {
                    $project: {
                        _id: 0,
                        k: '$_id',
                        v: '$count',
                    },
                },
            ],
            // Same as above but for class instead
            class: [
                { $sortByCount: '$class' },
                {
                    $project: {
                        _id: 0,
                        k: '$_id',
                        v: '$count',
                    },
                },
            ],
        },
    },
    {
        // Now apply the $arrayToObject for both class and race.
        $addFields: {
            // Will override the existing class and race arrays
            // with their respective object representation instead.
            class: { $arrayToObject: '$class' },
            race: { $arrayToObject: '$race' },
        },
    },
];

db.races.aggregate(aggregatorOpts)

Lo que produce lo siguiente:

[
  {
    "race": {
      "Halfling": 3,
      "Naga": 2
    },
    "class": {
      "Hunter": 3,
      "Rogue": 1,
      "Fighter": 1,
    }
  }
]

Si está satisfecho con el formato de salida proporcionado por @Asya, puede eliminar el $project y $addFields etapas, y simplemente deje el $sortByCount parte en cada canalización secundaria.

Con estas nuevas funciones, la agregación es mucho más fácil de ampliar con recuentos adicionales. Simplemente agregue otra canalización de agregación en $facet .Es incluso un poco más fácil contar los subgrupos, pero eso sería una pregunta aparte.