Just started mongo and started having issue with querying already. i have a collection called ‘externalTransaction’ and i want to write a equivalent of this mysql query:
select transactionCode,
sum(amount) as totalSum,
count(amount) as totalCount
from externalTransaction
where transactioncode in ('aa','bb','cc')
group by sum(amount)
below is my attempt:
{
"collectionName": "externalTransaction",
sort: {transactionCode:-1},
query: {this._id: {$in:['aa','bb','cc']}},
mapReduce:{
'map': 'function(){
emit(this.transactionCode, this.amount);
}',
'reduce': 'function(key, values){
var result = {count: 0, sum: 0.0};
values.forEach(function(value) {
result.count++
result.sum += value.amount;
});
return result;
}',
'out' : 'sumAmount'
}
}
the above query give me a result set looking like this:
_id value.count value.sum
ct 2.0 NaN
bb 40.0 NaN
fg 71.0 NaN
fd 36.0 NaN
sd 5.0 NaN
as 4.0 NaN
aa 71.0 NaN
df 4.0 NaN
cc 10.0 NaN
From the documentation with the version 2.0.6 i can’t use the aggregation framework just yet so how to handle simple queries like mine in mongo. thanks for reading and excuse the triviality of my question.
You have a few errors in your
mapandreducefunctions. First, inmapyou emit a simple number, and in reduce you try to takeamountof a number. I bet, it doesn’t have that property. Second, outputs ofmapandreducemust be uniform, becausereduceis supposed to be runnable over partially reduced results. Try these functions: