var map_function=function(){
for(var i=0;i<this.items.length; i++){
var key=this.items[i].item_name;
var value={
count :1,
qty:this.items[i].qty
};
emit(key, value);
}
}
var reduce_function=function(key, values){
reducedValue={count:0, qty:0};
for(var i=0; i<values.length; i++){
reducedValue.count +=values[i].count;
reducedValue.qty += values[i].qty;
}
return reducedValue;
}
var finalize_function=function(key, value){
value.avg=value.qty/value.count;
return value;
}
db.order.mapReduce(
map_function,
reduce_function,
{
out:{merge:"map_reduce_example"},
query:{order_date:{$gt: new Date('2012-02-01')}},
finalize:finalize_function
}
)
db.map_reduce_example.find()