Last active
April 13, 2021 15:05
-
-
Save trojanh/13a7b44055b6f2bc2dcabf546d39b182 to your computer and use it in GitHub Desktop.
Mongodb Aggregate with conditional groupBy and projections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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