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

358
Visualizações
MongoDB aggregation sum values and group by property

I have a collection that looks like this

{
 balance: string
 symbol: string
 address: string
}

I want to query that collection using an aggregation as following:

input array addresses[]

query collection where collection.address contained in provided address Array and SUM all balances grouped by symbol.

The desired output should look like this:

[
  {symbol: xy, balance: summedBalanceForThisSymbol},
  {symbol: yz, balance: summedBalanceForThisSymbol},
]

I am rather new to mongoDB, this is what I have which doesnt work at all.

  const pipe = [
        {
            match: [
                {
                    address: { $in: addresses } //addresses is an array of string values
                }
            ]
        },
        {
            group: {
                objectId: "$symbol",
                balance: { $sum: "$balance" }
            }
        }
    ]

I have to use objectId instead of _id because the SDK I am using requires to do so. I also need the string balance values to be converted to a number (I guess double) before summing up.

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

0

You are very close, you just have some minor syntax errors, this is how you should do it:

(One thing to mentioned is this requires balance to be a valid number string, if not the pipeline will throw an error)

db.collection.aggregate([
  {
    $match: {
      address: {
        $in: addresses
      }
    }
  },
  {
    $group: {
      _id: "$symbol",
      sum: {
        $sum: {
          "$toInt": "$balance"
        }
      }
    }
  }
])

Mongo Playground

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