Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trojanh/13a7b44055b6f2bc2dcabf546d39b182 to your computer and use it in GitHub Desktop.
Save trojanh/13a7b44055b6f2bc2dcabf546d39b182 to your computer and use it in GitHub Desktop.
Mongodb Aggregate with conditional groupBy and projections
db.getCollection('panData').aggregate([
{ $match: { createdAt: { $gte: '2020-04-01T18:30:00.000Z' } } },
{
$group: {
_id: { partner: '$productCode', project: '$source' },
project: { $sum: { $cond: [{ $eq: ['$cached', true] }, 1, 0] } },
apiHits: { $sum: { $cond: [{ $eq: ['$cached', true] }, 1, 0] } },
dbHits: { $sum: { $cond: [{ $eq: ['$cached', false] }, 1, 0] } },
hits: { $sum: 1 }
}
},
{
$project: {
_id: 0,
productCode: '$_id.partner',
source: '$_id.project',
apiHits: 1,
dbHits: 1,
hits: 1,
totalCost: { $multiply: ['$apiHits', 3.25] }
}
},
{
$lookup: {
from: 'panData',
let: { usageProductCode: '$productCode' },
pipeline: [
{
$match: {
createdAt: { $gte: '2020-04-01T18:30:00.000Z' },
$expr: {
$and: [{ $eq: ['$productCode', '$$usageProductCode'] }]
}
}
},
{ $count: 'count' }
],
as: 'panData'
}
},
{ $addFields: { panHits: { $sum: '$panData.count' } } },
{ $addFields: { panCost: { $multiply: ['$panHits', 0.75] } } },
{ $project: { panData: 0 } };
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment