Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Grupo anidado en canalización de agregación mongodb

Estoy usando Mongo DB y tengo una lista de objetos que necesito agrupar en categoría -> subcategoría -> diferentes tipos de subcategoría agrupados. Puede encontrar el código en este patio de recreo de mongodb > https://mongoplayground.net/p/BfR7FT28XKN

Creo la categoría de grupo -> todas las subcategorías. Pero, ¿cómo puedo agrupar la subcategoría con el mismo nombre?

Mi objetivo es lograr algo así:

 { "_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", } ] }, ] }

Gracias

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Esto es lo que necesitas. Primero debe agrupar por categoría y subcategoría. He empujado el documento completo en tipos. Puede filtrar los campos o hacer cambios según sus requisitos.

 [{ "$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" } } } }]

Elimine types: "$docs" de la última etapa y esto es lo que obtendría

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

Zona de juegos https://mongoplayground.net/p/nwyAivJOZj5

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!