Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda