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

时间:2012-06-26 16:23:17

标签: mongodb aggregation-framework

刚开始使用mongo并且已经开始查询问题了。我有一个名为'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的文档中我还不能使用aggregation framework,所以如何在mongo中处理像我这样的简单查询。感谢阅读和原谅我的问题的微不足道。

1 个答案:

答案 0 :(得分:2)

您的mapreduce函数中存在一些错误。首先,在map中,您会发出一个简单的数字,而在简化中,您会尝试使用amount的数字。我打赌,它没有那个属性。其次,mapreduce的输出必须是统一的,因为reduce应该可以在部分缩减的结果上运行。试试这些功能:

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;
}