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

162
Vistas
mongodb GROUP BY and COUNT an Array within Document

Given: A single document in collection. The Document contains an array. (i.e. Only one document entry exist in Collection)

Expectation : perform group by on city and print counts

Sample Data:

{
name: "ABC Bank",
hospitalList: [
  {city: "Delhi", hspName: "EEE hospital"},
  {city: "Delhi", hspName: "FFF hospital"},
  {city: "Surat", hspName: "MMM hospital"},
  {city: "Noida", hspName: "GGG hospital"},
  {city: "Surat", hspName: "HHH hospital"},
  {city: "Surat", hspName: "NNN hospital"},
  {city: "Surat", hspName: "PPP hospital"},
]
}

Expected Output:

Delhi - 2
Noida - 1
Surat - 3

Tried (but did NOT work)

$group: {
  _id: "hospitalList.city",
  count: { $sum: 1 }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

  • $match - to match the document bank name
  • $unwind - split the array of object in own document
  • $group - to group it by city then calculate count
db.collection.aggregate([
  {
    $match: {
      name: "ABC Bank"
    }
  },
  {
    "$unwind": "$hospitalList"
  },
  {
    $group: {
      _id: "$hospitalList.city",
      count: {
        $sum: 1
      }
    }
  }
])

Mongo playground: https://mongoplayground.net/p/Ac7RkJd7vU9

as per expected output: Mongo playground: https://mongoplayground.net/p/zeqB7P-BYmI

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