Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
Mongo condicionalmente suma valores en la tubería del proyecto

Estoy tratando de agregar una tubería de proyecto donde los valores son mayores que 100, los valores son campos dentro y objetos que forman parte de una matriz. Tengo algo como esto:

Base de datos:

---Colección de Clientes---

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

---Cobro de Facturas---

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

Y ESTA ES MI CONSULTA:

 { $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 } } } } }

Entonces la salida debería ser:

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

Estoy usando Mongo 3.6.3.

También en el futuro agregaré "invoicesAmountLesserThanOneHundred", el mismo método, pero por menos de 100, por supuesto.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

usar $filter antes $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" } } } ])

parque infantil mongo


usar $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 } } ] } } } } } ])

parque infantil mongo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!