Database
[{to:"0x123457baeb62c530cf369853e15ed25d0c82a866",from:"0x4321f7c477ccab3f95913b9d8cdf35a1caf25555",quantity:5,tokenAddress:"0x12129ec85eebe10a9b01af64e89f9d76d22cea18",},{to:"0x123457baeb62c530cf369853e15ed25d0c82a866",from:"0x0000000000000000000000000000000000000000",quantity:5,tokenAddress:"0x12129ec85eebe10a9b01af64e89f9d76d22cea18"},{to:"0x4321f7c477ccab3f95913b9d8cdf35a1caf25555",from:"0x0000000000000000000000000000000000000000",quantity:5,tokenAddress:"0x12129ec85eebe10a9b01af64e89f9d76d22cea18"},{to:"0x4321f7c477ccab3f95913b9d8cdf35a1caf25555",from:"0x0000000000000000000000000000000000000000",quantity:5,tokenAddress:"0x12129ec85eebe10a9b01af64e89f9d76d22cea18"}]
Query
db.collection.aggregate([{$project:{data:[{walletAddress:"$from",quantity:{"$multiply":["$quantity",-1]},tokenAddress:"$tokenAddress"},{walletAddress:"$to",quantity:"$quantity",tokenAddress:"$tokenAddress"}]}},{$unwind:"$data"},{$group:{_id:"$data.walletAddress",quantity:{$sum:"$data.quantity"},tokenAddress:{$first:"$data.tokenAddress"}}},{$match:{_id:{$in:["0x4321f7c477ccab3f95913b9d8cdf35a1caf25555","0x123457baeb62c530cf369853e15ed25d0c82a866"]}}}])