'MongoDB and ReactJS aggregation : how to return the count of items?

Despite looking at many other posts I can't figure out what I'm doing wrong. I want to do a simple "count and group by", so I found out I need to use collection.aggregate....

Here is my [pubkey].ts where I execute the aggregation, basically I want to count each entry grouped by address sp I'd get something like :

{address1: 6},
{address2: 1},
...
import { connect } from '../../../utils/db'
import Raffles from '../../../utils/db/raffle'

export default async function handler(req, res) {
    const { method } = req
    const { pubkey } = req.query
    await connect()
    switch (method) {
        case 'POST':
          ...
          break
        case 'GET':
            try{
                const ticket = await Raffles.aggregate([{
                    "$match": {
                        "address": pubkey
                    }
                },{
                    "$count": { $sum: 1}
                }])

                res.status(201).json({ success: true, data: ticket })
            } catch (error){
                res.status(400).json({ success: false, data: error })
            }
            break
        default:
          res.status(400).json({ success: false })
          break
      }
}

I can't figure out how to do the summing part, if I replace "$count": "xxyz" I get a success but right now with "$count" : {$sum: 1} I get an error

Any ideas ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source