Created
February 11, 2021 14:40
-
-
Save demian85/c64765dad5481caa758292288eeea557 to your computer and use it in GitHub Desktop.
mongodb insane aggregation query
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
.aggregate([ | |
{ | |
$lookup: { | |
from: 'snapshots', | |
let: { address: '$address' }, | |
pipeline: [ | |
{ | |
$match: { | |
$expr: { | |
$and: [ | |
{ $eq: ['$$address', '$address'] }, | |
{ | |
$gte: ['$timestamp', snapshotDate], | |
}, | |
], | |
}, | |
}, | |
}, | |
{ | |
$sort: { | |
timestamp: 1, | |
}, | |
}, | |
{ | |
$limit: 1, | |
}, | |
], | |
as: 'snapshots', | |
}, | |
}, | |
{ | |
$unwind: { | |
path: '$snapshots', | |
preserveNullAndEmptyArrays: true, | |
}, | |
}, | |
{ | |
$group: { | |
_id: '$type', | |
balance: { | |
$sum: '$snapshots.balance', | |
}, | |
details: { | |
$addToSet: { | |
address: '$address', | |
name: '$name', | |
}, | |
}, | |
}, | |
}, | |
{ | |
$project: { | |
_id: 0, | |
type: '$_id', | |
balance: 1, | |
details: 1, | |
}, | |
}, | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example response: