coder_B
coder_B

Reputation: 110

Conditional $sum query in mongoDB

I want to get sum of filed reqAmount in my mongodb database of a particular user.

Here is the schema

enter image description here

const userid = req.body.userId;
const id = mongoose.Types.ObjectId(userid);


fundReq.aggregate([
    { $match : { userId : id } },
    {
     $group: {
         _id :  '',
         total: {$sum : "$reqAmount"}
     }
    }
],function (err, result) {
    if (err) throw err;
    else res.json(result);
})

but getting null in result...

Upvotes: 0

Views: 205

Answers (1)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

it's Working Fine For You

const ObjectId = require('mongodb').ObjectId;

function fnGetTotalCollectionAmount(callback) {
    TransactionModel.aggregate([
        {
            $match: { '_id': ObjectId(productId) }
        },
        {
            $group: {
                _id: null,
                grandTotal: {
                    $sum: '$subTotal'
                }
            }
        }
    ]).exec(function (err, transaction) {
        if (err) {
            return callback(err);
        } else {
            return callback(transaction[0].grandTotal);
        }
    });
}

Upvotes: 4

Related Questions