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

634
Visualizações
How to group and a count fields in a mongoDB collection

I'm really new to mongodb coming from a sql background and struggling to work out how to run a simple report that will group a value from a nested document with a count and in a sort order with highest count first.

I've tried so many ways from what I've found online but I'm unable to target the exact field that I need for the grouping.

Here is the collection.

{
    "_id": {
        "$oid": "6005f95dbad14c0308f9af7e"
    },
    "title": "test",
    "fields": {
        "6001bd300b363863606a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd300b363863606a815e"
                },
                "title": "Title Two",
                "datatype": "string"
            },
            "section": "Section 1",
        },
        "6001bd300b363863423a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd3032453453606a815e"
                },
                "title": "Title One",
                "datatype": "string"
            },
            "section": "Section 1",
        },
        "6001bd30453534863423a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd300dfgdfgdf06a815e"
                },
                "title": "Title One",
                "datatype": "string"
            },
            "section": "Section 1",
        }
    },
    "sections": ["Section 1"]
}

The result I need to get from the above example would be:

"Title One", 2

"Title Two", 1

Can anyone please point me in the right direction? Thank you so much.

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

0

Having dynamic field names is usually a poor design.

Try this one:

db.collection.aggregate([
   { $set: { fields: { $objectToArray: "$fields" } } },
   { $unwind: "$fields" },
   { $group: { _id: "$fields.v.field.title", count: { $count: {} } } },
   { $sort: { count: -1 } }
])
over 4 years ago · Santiago Trujillo Relatório

0

Here's another way to do it. The $project throws away everything except for the deep-dive to "title". Then just $unwind and $sortByCount.

db.collection.aggregate([
  {
    "$project": {
      "titles": {
        "$map": {
          "input": {
            "$objectToArray": "$fields"
          },
          "in": "$$this.v.field.title"
        }
      }
    }
  },
  {
    "$unwind": "$titles"
  },
  {
    "$sortByCount": "$titles"
  }
])

Try it on mongoplayground.net.

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