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

101
Visualizações
Mongo conditionally sum values in project pipeline

I'm trying to add in a project pipeline where the values are greater than 100, the values are fields inside and object which are part of an array. I have something like this:

Database:

---Clients Collection---

client: {
    _id: 1,
    taxID: aldsfkjasdlñfk
    // other stuff
}

---Invoices Collection---

invoice: {
    _id: 1,
    clientID: 1,
    total: 50
},
invoice: {
    _id: 2,
    clientID: 1,
    total: 150
},
invoice: {
    _id: 3,
    clientID: 1,
    total: 200
}

AND THIS IS MY QUERY:

{
     $lookup: {
          from: 'invoices',
          localField: '_id',
          foreignField: 'client.id',
          as: 'invoices'
     }
},
{
     $project: {
          id: 1,
          taxID: aldsfkjasdlñfk,
          invoicesAmountGreaterThanOneHundred: {
               $sum: {
                   $cond: { if: { $gte: ['$invoices.total', 100] }, then: '$invoices.total', else: 0 }
               }
          }
     }
}

So the output should be:

{
     _id: 1.
     taxID: aldsfkjasdlñfk,
     invoicesAmountGreaterThanOneHundred: 350
}

I'm using Mongo 3.6.3.

Also in the future I will add a "invoicesAmountLesserThanOneHundred", same method, but for lesser than 100 of course.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

use $filter before $sum

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoices": {
        "$filter": {
          "input": "$invoices",
          "as": "i",
          "cond": { $gte: [ "$$i.total", 100 ] }
        }
      }
    }
  },
  {
    $project: {
      id: 1,
      taxID: 1,
      invoicesAmountGreaterThanOneHundred: {
        $sum: "$invoices.total"
      }
    }
  }
])

mongoplayground


use $reduce

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoicesAmountGreaterThanOneHundred": {
        $reduce: {
          input: "$invoices",
          initialValue: "",
          in: {
            $sum: [
              "$$value",
              {
                $cond: {
                  if: { $gte: [ "$$this.total", 100 ] },
                  then: "$$this.total",
                  else: 0
                }
              }
            ]
          }
        }
      }
    }
  }
])

mongoplayground

about 4 years ago · Juan Pablo Isaza 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