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

204
Visualizações
How to get a sorted list of most used values for a field in a mongodb collection

I have some documents resembling the following structure:

{ 
   "name": "item_1",
   "category": ["a", "b"]
},
{ 
   "name": "item_2",
   "category": ["c"]
},
{ 
   "name": "item_3",
   "category": ["a", "c"]
},
{ 
   "name": "item_4",
   "category": ["a"]
},
{ 
   "name": "item_5",
   "category": ["a"]
}

I'm trying to get a sorted list of the most used values for the category field in all documents within the collection.

So in this example, the return value I'm expecting should be something like this:

[
   {
      "category": "a",
      "count": 4
   },
   {
      "category": "c",
      "count": 2
   },
   {
      "category": "b",
      "count": 1
   }
]

Is there a way to make such a query in mongoose?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Demo - https://mongoplayground.net/p/sBpwwvowXLH

Use aggregation query to $unwind your category into separate documents $group them back by category and get the count

$sum

db.collection.aggregate({
  "$unwind": "$category"
},
{
  "$group": {
    "_id": "$category",
    count: { $sum: 1 }
  }
})
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