【发布时间】:2014-08-17 23:41:59
【问题描述】:
我仍然使用 mongoDB 完成了这个 map/reduce/finalize 函数。
这就是我需要 mongoDB 执行聚合的方式:
db.house_results.mapReduce(function(){
emit(this.house_name.toLowerCase(),this);
},function(key,values){
var house = {name:key,address:"",description:"",photo:[],lat:0,lng:0,rooms:[]};
values.forEach(function(house_val) {
/*Address*/
if(house.address=="")
house.address = house_val.house_address;
/*Photo*/
if(!house_val.photo in house.photo)
house.photo.push(house_val.house_photo);
/*Description*/
if(house.description=="")
house.description = house_val.house_description;
/*LAT - LNG*/
if(house.lat==0 || house.lng==0){
var house_position = house_val.house_position;
if(house_position && house_position.lat && house_position.lng){
house.lat = house_position.lat;
house.lng = house_position.lng;
}
}
if(house.lat==0 || house.lng==0){
if(house_val.house_lat && house_val.house_lng){
house.lat = house_val.house_lat;
house.lng = house_val.house_lng;
}
}
if(house_val.rooms)
house.rooms.push(house_val.rooms);
});
return house;
},
{
out : "map_reduce_house_test",
finalize:function(key,house_val){
if(house_val.address==undefined){ // JUST ONE RESULT IN MAP FUNCTION -> REDUCE FUNCTION IS IGNORED -> FINALIZE IS SOLUTION
var house = {name:key,address:"",description:"",photo:[],lat:0,lng:0,rooms:[]};
/*Address*/
if(house.address=="")
house.address = house_val.house_address;
/*Photo*/
if(!house_val.photo in house.photo)
house.photo.push(house_val.house_photo);
/*Description*/
if(house.description=="")
house.description = house_val.house_description;
/*LAT - LNG*/
if(house.lat==0 || house.lng==0){
var house_position = house_val.house_position;
if(house_position && house_position.lat && house_position.lng){
house.lat = house_position.lat;
house.lng = house_position.lng;
}
}
if(house.lat==0 || house.lng==0){
if(house_val.house_lat && house_val.house_lng){
house.lat = house_val.house_lat;
house.lng = house_val.house_lng;
}
}
if(house_val.rooms)
house.rooms.push(house_val.rooms);
return house;
}else
return house_val;
}
}
);
有没有办法简化这些功能和/或更好地使用聚合 mongodb 的功能?
哪种方法可能是最快和更简单的方法?
谢谢!
【问题讨论】:
标签: mongodb mapreduce aggregation-framework