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

163
Visualizações
is there is way to multi group in mongodb

there is way to multi group in mongodb ? document i have and want to query it

[ { _id: '1615658138236', englishName: 'samsung smart tv 50', screen_resulation: '4K', screen_size: '50' }, { _id: '1615750981674', englishName: 'lg tv 55 led uhd', screen_resulation: 'UHD', screen_size: '55' }, { _id: '1615791834538', englishName: 'samsung smart 55 inch crystal 4k', screen_resulation: '4K', screen_size: '55' } ]

for example i have 2 unknown fields i use this method to get them

    for (let i = 0; i < result[0].filters.length; i++) {
      const item = result[0].filters[i].key;
      groupBy[item] = `$${item}`;
    }

and i try to query mongodb to get count of every field

const products = await Product.aggregate([
      {
        $match: {
          category,
        },
      },
      {
        $group: {
          _id: groupBy,
          count: {
            $sum: 1,
          },
        },
      },
      {
        $sort: { count: -1 },
      },
    ]);

result i get

[
  { _id: { screen_size: '50', screen_resulation: '4K' }, count: 1 },
  { _id: { screen_size: '55', screen_resulation: 'UHD' }, count: 1 },
  { _id: { screen_size: '55', screen_resulation: '4K' }, count: 1 }
]

what i expect is :

[
  { _id: { screen_size: '50' }, count: 1 },
  { _id: { screen_size: '55' }, count: 2 },
  { _id: { screen_resulation: '4K' }, count: 2 },
  { _id: { screen_resulation: 'UHD' }, count: 1 },
]

i really find mongodb is great but very hard for me i dont know why

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

0

You can use $facet for multiple aggregation pipelines.

db.collection.aggregate([
  {
    "$facet": {
      "screen_size_count": [
        {
          "$group": {
            "_id": "$screen_size",
            "count": {
              $sum: 1
            }
          }
        }
      ],
      "screen_resulation_count:": [
        {
          "$group": {
            "_id": "$screen_resulation",
            "count": {
              $sum: 1
            }
          }
        }
      ]
    }
  }
])

Mongo Playground: https://mongoplayground.net/p/cnEY8NV4HNs

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