如何合并来自两个不同集合的文档。
从shopping_collection
我们可以获得购买历史,
为了获得每个购买历史的详细信息,我需要从detailed_shopping_list_collection
获得信息
但aggregate
似乎不可能做到这一点,因为集合不同?
如何使用mapreduce获取它?
shopping_collection
{
"name": "Mary",
"gender": "M",
"birthday": new Date("1980-04-01T08:00:00+0800"),
"records": [
{
"BUY_DATE": new Date("1996-02-08T08:00:00+0800"),
"SEQ_NO": 768,
},
{
"BUY_DATE": new Date("1996-02-06T08:00:00+0800"),
"SEQ_NO": 595,
}
}
详细_跳跃列表_集合
{
"BUY_DATE": new Date("1996-02-08T08:00:00+0800"),
"SEQ_NO": 768
"ITEM_NAME": "iphone4s"
"PRICE": 500
},
{
"BUY_DATE": new Date("1996-02-08T08:00:00+0800"),
"SEQ_NO": 768
"ITEM_NAME": "iphone4s"
"PRICE": 500
},
{
"BUY_DATE": new Date("1996-02-08T08:00:00+0800"),
"SEQ_NO": 768
"ITEM_NAME": "macbook"
"PRICE": 700
}
预期汇总结果
{
"name": "Mary",
"gender": "M",
"birthday": new Date("1980-04-01T08:00:00+0800"),
"records": [
{
"BUY_DATE": new Date("1996-02-08T08:00:00+0800"),
"SEQ_NO": 768,
"PURCHASE_HISTORY":[
{"ITEM_NAME": "iphone4s"
"PRICE": 500},
{"ITEM_NAME": "iphone4s"
"PRICE": 500},
{"ITEM_NAME": "macbook"
"PRICE": 700}
]
"UNIQUE_PURCHASE_ITEMS":[ "iphone4s", "macbook"
]
},
{
"BUY_DATE": new Date("1996-02-06T08:00:00+0800"),
"SEQ_NO": 595,
}
}
您试图实现的目标应该在客户端使用多个查询来完成,因为mapreduce不能代替联接。然而,一些人提出了一些有趣的方法,例如。http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/.
请检查以下查询:
// MAP FUNCTION LOGIC
var map = function(){
var arr = new Array();
this.records.forEach(function(doc){
var temp = db.detailed_shopping_list_collection.find(
{"BUY_DATE": doc.BUY_DATE, "SEQ_NO" : doc.SEQ_NO});
arr.push(temp);
});
emit(this._id,{"name" : this.name, "gender" :
this.gender, "birthday" : this.birthday, "records" : arr );
}
// REDUCE FUNCTION LOGIC
var reduce = function(id , doc){ return doc; }
// MAP REDUCE CALL
db.shopping_collection.mapReduce( map,reduce,{out: {inline :1}} );