-1

I use MongoDB and Mongoose as my ODM in next.js and i'm trying group by user and calculate all amounts

Here is my Schema:

const bonusFillSchema = new mongoose.Schema({
    user: {
        type: Schema.Types.ObjectId,
        required: true,
    },
    amount: {
        type: Number,
        required: true,
    }, {
    timestamps: true
})
}

let Dataset = mongoose.models.bonusFill || mongoose.model('bonusFill', bonusFillSchema)
export default Dataset 

I'm just trying to get every bonusFill record, group by each user and calculate all amount.

import Fill from '../../../models/bonusFill'
const fills = await Fill.find()

Output

{
    "fills": [
        {
            "_id": "63244477301b6fd9d3116d37",
            "user": "631ce46b9bed2e97ba77a0a3",
            "amount": 100,
            "createdAt": "2022-09-16T09:40:07.179Z",
            "updatedAt": "2022-09-16T09:40:07.179Z",
            "__v": 0
        },
        {
            "_id": "63244487301b6fd9d3116d67",
            "user": "631ce46b9bed2e97ba77a0a3",
            "amount": 120,
            "createdAt": "2022-09-16T09:40:23.017Z",
            "updatedAt": "2022-09-16T09:40:23.017Z",
        },
{
            "_id": "63244487301b6fd9d3116d67",
            "user": "632ce66b9bqd2e97baa795a4",
            "amount": 50,
            "createdAt": "2022-09-16T09:40:23.017Z",
            "updatedAt": "2022-09-16T09:40:23.017Z",
        },
    ]
}

Expected Output

{
    "fills": [
        {
            "user": "631ce46b9bed2e97ba77a0a3",
            "amount": 220,
        },
        {
            "user": "632ce66b9bqd2e97baa795a4",
            "amount": 50,
        },
    ]
}

Any solutions? Thank you.

1 Answers1

-1

i found solution. thanks!

const fills = await Fill.aggregate([
        {"$group": {_id: "$_id", user: {"$first": "$user"}, amount: {$sum: "$amount"}}}
    ]).sort({ amount: 'desc' })
res.status(200).json({sponsor: fills})