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.
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" } } } ]) 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 } } ] } } } } } ])