Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Mongodb, aggregate nr of items in $group

I'm doing some aggregation to get some statistics on a how many products there are in cateories.

After some piping I'm down to this:

[
  {
     topCategory: "Computer",
     mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Laptop"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },

]

Wanted output:

[
  {
    name: "Computer",
    count: 4,
    mainCategories: [
      {
         name: "Laptop",
         count: 2
      },
      {
         name: "Stationary",
         count: 2
      }
    ]
  }
]

My query so far:

let query = mongoose.model('Product').aggregate([
    {
      $match:  {
        project:  mongoose.Types.ObjectId(req.params.projectId)
      }
    },
    { $project:  {
        _id: 0,
        topCategory: '$category.top',
        mainCategory: '$category.main',
      }
    },
 ]);

I know I need to use $group combined with $sum. I tried different way's but can't get it work.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

In this case first you should group by mainCategory and then group by topCategory as below

db.collection.aggregate({
  $group: {
    _id: "$mainCategory",
    "count": {
      $sum: 1
    },
    "data": {
      "$push": "$$ROOT"
    }
  }
}, {
  "$unwind": "$data"
}, {
  "$group": {
    "_id": "$data.topCategory",
    "count": {
      "$sum": 1
    },
    "mainCategories": {
      "$addToSet": {
    "name": "$_id",
    "count": "$count"
      }
    }
  }
}).pretty()
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda