提问者:小点点

如何用json在mongodb 2.0.6中编写一个简单的聚合查询API


我有一个名为'externalTransaction'的集合,我想写一个等效的这个mysql查询:

select transactionCode, 
       sum(amount) as totalSum, 
       count(amount) as totalCount 
from externalTransaction 
where transactioncode in ('aa','bb','cc') 
group by sum(amount)

以下是我的尝试:

{
 "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'
 }

}

上面的查询给了我一个如下所示的结果集:

_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

从留档的版本2.0.6我还不能使用聚合框架,所以如何在mongo处理像我这样的简单查询。感谢阅读,原谅我的问题的琐碎。


共1个答案

匿名用户

您的mapduce函数中有一些错误。首先,在map中,您发出一个简单的数字,在duce中您尝试获取数字的。我敢打赌,它没有这个属性。其次,mapduce的输出必须是统一的,因为duce应该可以在部分缩小的结果上运行。试试这些函数:

var map = function() {
  emit(this.transactionCode, {sum: this.amount, count: 1})
}

var reduce = function(k, vals) {
  var result = {sum: 0, count: 0};

  vals.forEach(function(v) {
    result.sum += v.sum;
    result.count += v.count;
  });
  return result;
}