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

120
Vistas
Nested group in mongodb aggregation pipeline

I'm using Mongo DB and I have a list of object that I need to group in category -> subcategory -> different types of subcategory grouped together. You can find the code in this mongodb playground > https://mongoplayground.net/p/BfR7FT28XKN

I create the group category -> all the sub category. But how can I group the subcategory with the same name?

My goal is to achieve something like that:

{
    "_id": "Food and Drink",
    "subCategories": [
      {
        "details": "Wine Bar",
        "subCategory": "Bar",
      },
      {
        "details": "Jazz and Blues Cafe",
        "subCategory": "Nightlife",
      },
      {
        "subCategory": "Restaurants",
        "types": [
              {
                "details": "Mediterranean",
                "subCategory": "Restaurants",
              },
              {
                "details": "Mexican",
                "subCategory": "Restaurants",
              }
           ]
       },
      
    ]
  }

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here's what you need. You need to group by both category and sub category first. I have pushed complete document in types. You can filter the fields or do changes as per your requirements.

[{
"$match": {
  "category": {
    "$ne": null
  },
  "subCategory": {
    "$ne": null
  }
 }
},
{
 $group: {
  _id: {
    cat: "$category",
    sub: "$subCategory",
    
   },
   docs: {
    $push: "$$ROOT"
   }
 }
},
{
$group: {
  _id: "$_id.cat",
  subCategories: {
    $push: {
      subCategory: "$_id.sub",
      types: "$docs"
    }
  }
 }
}]

Remove types: "$docs" from last stage and this is what you'd get

[{
"_id": "Community",
"subCategories": [
  {
    "subCategory": "Education"
  },
  {
    "subCategory": "Disabled Persons Services"
  }
 ]
},
{
 "_id": "Food and Drink",
 "subCategories": [
  {
    "subCategory": "Bar"
  },
  {
    "subCategory": "Nightlife"
  },
  {
    "subCategory": "Restaurants"
  }
 ]
}]

Playground https://mongoplayground.net/p/nwyAivJOZj5

about 4 years ago · Juan Pablo Isaza 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