I'm doing a calculation for a real-time browser game, where users can invest some of their balances to the site. I need to update their invest's based on AN_AMOUNT_FROM_SITE
and their percentage of shares (see PROFIT
line). This function needs to run every 20-100 ms because AN_AMOUNT_FROM_SITE
is coming consistently.
When this process finish, I'm saving a few unimportant data in callback()
.
When FUNDS
collection has a few hundred document, this process will be very slow. Are there any ways I can reduce this process with Mongo to make it more efficient?
FUNDS.aggregate().group({ //get sum of invested amounts
_id: '$id1',
invest_total: { $sum: '$invest_amount'}}).exec(function ( e1, d ) {
if( !e1 && d ){
FUNDS.find().exec(function( e2, invests ){ //find all invests
if ( !e2 && invests ){
//calculate PROFIT value to each invest according to their rates (it can be +/-)
for (var i = 0; i < invests.length; i++) {
var invest_amount = invests[i].invest_amount,
invest_id = invests[i].invest_id,
PROFIT = AN_AMOUNT_FROM_SITE * invest_amount / d[0].invest_total; //
//update each invest
FUNDS.findOneAndUpdate({ 'invest_id': invest_id }, { $inc: { 'invest_profit': profit } }, function(e3) {
callback()
});
};
}
})
}
})