Skip to content

Instantly share code, notes, and snippets.

@demian85
Created February 11, 2021 14:40
Show Gist options
  • Save demian85/c64765dad5481caa758292288eeea557 to your computer and use it in GitHub Desktop.
Save demian85/c64765dad5481caa758292288eeea557 to your computer and use it in GitHub Desktop.
mongodb insane aggregation query
.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,
},
},
])
@demian85
Copy link
Author

Example response:

 [
  {
    "_id": {
      "$oid": "6025431212a6da56e60706ef"
    },
    "total": 57652083,
    "details": [
      {
        "address": "0xfc293b1065f627edfb600663652d42cd7a397029",
        "name": "Company #1"
      }
    ],
    "type": "company"
  },
  {
    "_id": {
      "$oid": "6025431212a6da56e60706f0"
    },
    "total": 285836388.02000034,
    "details": [
      {
        "address": "0x8b9ca4469c49ee4506b04315ffb6b21349052d67",
        "name": "Investor #2"
      },
      {
        "address": "0xe387606dd76f6f502cb9ef4d79dcab89ed04fcb2",
        "name": "Investor #1"
      }
    ],
    "type": "investor"
  },
  {
    "_id": {
      "$oid": "6025431212a6da56e60706f1"
    },
    "total": 65250000.00000007,
    "details": [
      {
        "address": "0x94e7b4c70e12abb2516773f2f06471a3031c94a7",
        "name": "Private sale future distribution 1"
      }
    ],
    "type": "circulating"
  },
  {
    "_id": {
      "$oid": "6025431212a6da56e60706f2"
    },
    "total": 108721732,
    "details": [
      {
        "address": "0x5b485df8f00080d515be666543b40904fbf9a3fd",
        "name": "Incentive #2"
      },
      {
        "address": "0xb291fbc677839d5b56a15cf0629300222676d57e",
        "name": "Incentive #1"
      }
    ],
    "type": "incentive"
  }
]``` 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment