如何通过使用Map / Reduce在MongoDB中合并两个集合

时间:2018-10-13 17:35:00

标签: mongodb mapreduce mongodb-query aggregation-framework

我想合并这两个集合,并且它具有“ name”变量作为公共字段。

// product collections   

db.products.insertOne( { name : "iPhone 5", Price : 600, company : "Apple"}) 
db.products.insertOne( { name : "Galaxy Note9", Price : 900, company : "samsung"}) 
db.products.insertOne( { name : "LG V40 ThinQ", Price : 800, company : "LG"}) 
db.products.insertOne( { name : "Watch", Price : 400, company : "Apple"}) 
db.products.insertOne( { name : "iPhone 7", Price : 900, company : "Apple"})

// product_review Collection

db.product_review.insertOne( { name : "Watch", comment: " Great Product" })
db.product_review.insertOne( { name : "Watch", comment: " AMAZING" })
db.product_review.insertOne( { name : "iPhone 7", comment: " Not bad" })
db.product_review.insertOne( { name : "iPhone 7", comment: " Expeinsive" })
db.product_review.insertOne( { name : "Galaxy Note9", comment: " Great Product" })
db.product_review.insertOne( { name : "Galaxy Note9", comment: " Great Product" })

// end of product_review collection.

我正在寻找的输出如下。一个名称和一个或多个注释,而不必在每个注释中重复该名称。应该是这样的。

{
    name: "iPhone 7", 
    Price: 900, 
    company: "Samsung", 
    comments :[ 
        {"comment": "Not bad"}, 
        {"comment": " Expeinsive"}
    ]
}

我当前的代码没有给我评论,它给了我名称和价格,并没有评论。

我找到了这段代码并试图采用它,但是它可以按我的意愿工作

// map for products collection 

var mapproducts = function() {
    var output = {
        name: this.name, 
        Price :this.Price, 
        company:this.company, 
        comment:0
    }
    if (this.Price == 0) {
        output.name = this.name;
    }

    emit(this.name, output);
};

// map for product_review collection

var map_product_review = function() {
    emit(this.name, {
        name: this.name, 
        comment:this.comment, 
        Price:0, 
        company: 0
    });
};

// Reduce function. 
// I believe that the  "IF condition" has to be done, is specific ways

 var r = function(key, values) {    
     var outs = { name: 1,comment: 1, Price: 0,company:0};    

     values.forEach(function(v){       
         outs.name = v.name; 

         if (v.comment == 0) {            
             outs.Price = v.Price;
             outs.company = v.company;
         }
     });

     return outs; 
};




db.products.mapReduce(mapproducts, r, {out: {reduce: ‘Result’}})
db.product_review.mapReduce(map_product_review, r, {out: {reduce: 'Result'}})

db.Result.find().pretty()

0 个答案:

没有答案