Mongodb mapreduce加入2个集合

时间:2018-10-15 20:57:48

标签: javascript mongodb mapreduce mongodb-query

我有2个收藏,我是Mongo MapReduce概念的新手。 我的收藏集Value如下

{
    "_id" : ObjectId("5bc4f20e1a80d2045029ccb7"),
    "name" : "Title 1",
    "value" : "value 1 for title 1"
}
{
    "_id" : ObjectId("5bc4f20e1a80d2045029ccb8"),
    "name" : "Title 1",
    "value" : "Value 2 for title1. "
}

{
    "_id" : ObjectId("5bc4f20e1a80d2045029ccb9"),
    "name" : "Title 2",
    "value" : " Definitely a motivational text!"
}

{
    "_id" : ObjectId("5bc4f20e1a80d2045029ccba"),
    "name" : "Title 2",
    "value" : "It's tough but I'm carrying on. "
}

其他收藏详细信息如下:

{
    "_id" : ObjectId("5bc4f2361a80d2045029d05b"),
    "name" : "Title 1",
    "totalValues" : 6.0000000000000000,
    "link": "Link1",
    "description" : "Some More Text to Make title 1 look better"
}

{
    "_id" : ObjectId("5bc4f2361a80d2045029d2eb"),
    "name" : "Title 2",
    "totalValues" : 2,
    "link": "Link2",
    "description" : "Some More Text to Make title 2 look better"
} ...

我希望输出结果为

{
“name” : “XXXXXXXX”,
“comments” : [ {“value”: “XXXXXXX”}, {“value”: “YYYYYYYY”}],
“totalValues” : 2,
“link”: “XXXXXXXXXX”,
“description”: “XXXXXXXXXXXXXXXXXX”
}

以及以下输出文档。请帮忙。

我尝试了以下代码:

var mapDetails = function(){
  var output = {name: this.name,totalValues :this.totalValues, description : this.description, link :this.link}

    emit(this.name, output);
};


var mapGpas = function() {
    emit(this.name,{name:this.name, value:this.value, totalValues:0, description: 0, link: 0});
};


var r = function(key, values) {    
 var outs = { name: 1,value: 1, description: 0,totalValues:0, link: 0};    
  values.forEach(function(v){       
    outs.name = v.name; 
    if (v.value == 0) {            
      outs.description = v.description;
      outs.totalValues = v.totalValues;              
      outs.link = v.link;
    }
  });
  return outs; 
};





res = db.Value.mapReduce(mapGpas, r, {out: {reduce: 'joined'}})
res = db.Details.mapReduce(mapDetails, r, {out: {reduce: 'joined'}})

db.joined.find().pretty()

0 个答案:

没有答案