mongoDB中的条件$ sum查询

cod*_*r_B 0 mongoose mongodb node.js

我想在特定用户的mongodb数据库中获取reqAmount的总和。

这是架构

在此处输入图片说明

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);
})
Run Code Online (Sandbox Code Playgroud)

但是结果为空...

vis*_*iya 5

对你来说很好

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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)