Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda