1

我正在尝试使用 map/reduce 计算一年的频率,这是代码

map = %Q{
  function(){
    emit({}, { 
      year: this.birthdate.getFullYear(),
      count: 1
    })
  }
}
reduce = %Q{
  function(key, values){
    var agg = { }
    values.forEach( function(value){
      if(agg[value.year]){
        agg[value.year] += value.count
      } else {
        agg[key] = value.count
      }
    })
    return agg
  }
}
User.map_reduce(map, reduce).out(inline: true)

它返回

=> [{"_id"=>{}, "value"=>{"2004"=>2.0, "2002"=>1.0, "2005"=>1.0}}] 

但是我的数据库中有很多年,这只是跟踪其中的 3 年。我怎样才能做到这一点?

4

1 回答 1

1

现在它的工作......这是代码

map = %Q{
  function(){
    var today = new Date()
    var age = today.getFullYear() - this.birthdate.getFullYear()
    var m = today.getMonth() - this.birthdate.getMonth()
    if (m < 0 || (m === 0 && today.getDate() < this.birthdate.getDate()))
        age--

    emit(age, { count: 1 })
  }
}
reduce = %Q{
  function(key, values){
    var sum = 0

    values.forEach( function(value){
      sum += value.count
    })

    return { count: sum }
  }
}

scoped.map_reduce(map, reduce).out(inline: true)
于 2012-11-01T01:31:08.800 回答