1

刚开始 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 中的简单查询。感谢您阅读并原谅我的问题的琐碎性。

4

1 回答 1

2

您的mapreduce功能有一些错误。首先,在map你发出一个简单的数字,在 reduce 你尝试取amount一个数字。我敢打赌,它没有那个属性。其次,map和的输出reduce必须是一致的,因为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;
}
于 2012-06-26T16:34:05.847 回答