我正在尝试使用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。我怎么能这样做?
答案 0 :(得分: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)