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

818
Visualizações
MongoDB - Calculate $sum of values in array containing array elements

I have an aggregation query producing an array containing array elements. How can I $sum the values and produce output similar to the following:

  { "additionalReminders": 7 }

This is an example of the data structure. Notice some of the array elements are empty and should be ignored or counted as 0:

  {
    "additionalReminders": [
      [
        "1",
        "1"
      ],
      [],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [
        "1"
      ],
      [],
      [],
      [
        "1"
      ]
    ]
  }

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

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

0

Here is what you're looking for:

db.collection.aggregate([
  {
    "$unwind": "$additionalReminders"
  },
  {
    "$unwind": "$additionalReminders"
  },
  {
    $group: {
      _id: null,
      "additionalReminders": {
        $sum: {
          "$toInt": "$additionalReminders"
        }
      }
    }
  },
  {
    $project: {
      _id: false,
      additionalReminders: true
    }
  }
])

Playground: https://mongoplayground.net/p/JInbHAmc_yV

The idea is to unwind your field a couple of times so as to get this output:

...
{
    "_id": ObjectId("5a934e000102030405000000"),
    "additionalReminders": "1"
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "additionalReminders": "1"
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "additionalReminders": "1"
  },
...

Then it's just a simple matter of summing up the $additionalReminders field, but not before we cast it to an Int.

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