我怎么能合并来自两个不同集合的文档

时间:2015-06-25 03:13:46

标签: mongodb mapreduce

我如何合并来自两个不同馆藏的文件。

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,
    }
}

detailed_shopping_list_collection

{
  "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,
    }
}

2 个答案:

答案 0 :(得分:0)

您尝试实现的目标应该在客户端使用多个查询完成,因为mapreduce不是替换连接。但是,有些人提出了一些有趣的方法,例如: http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/

答案 1 :(得分:0)

请检查以下查询:

// 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}} );