Call function inside aggregate


#1

hi I want to call a function inside the aggregate.
For Example I have a exchange function and I want to call it inside the $sum.
Here is my code but not work.

function exchange(curFrom, curTo, amount) {
var ex = Cpanel.Collection.Exchange.findOne({
base: curFrom
},
{
sort: {_id: -1}
});
return ex.rates[curTo] * amount;
}

Meteor.methods({
getIncome: function (selector) {

    var arr = [];
    var result = Inex.Collection.Journal.aggregate([

        {$unwind: "$transaction"},
        {
            $match: selector
        },
        {
            $group: {
                _id: {
                    account: "$transaction.account",
                    name: "$transaction.accountDoc.name",
                    currency: "$currencyId"
                },
                result: {$sum: exchange(curFrom,curTo,"$transaction.amount")}
            }
        }
    ]);

    }

})


#2

This is not at all Meteor-specific, but is rather a question about what you can and cannot do with MongoDB aggregations. I suggest reading up on that in their documentation.

You cannot call arbitrary JS functions within the aggregation pipeline. You’ll need to understand what’s possible with aggregations and then devise ways how you can accomplish what you need.
But basically you will probably have to split up your aggregations into multiple passes, processing the results in JS code, then storing things back and performing further aggregations, or similar.
And check out MongoDB’s map reduce capabilities, in there you can actually execute some (limited) JavaScript directly in the database.

HTH


#3

seeekr ,Thank for your reply