使用Map / Reduce在MongoDB中的2个集合之间合并一个公共字段?

时间:2018-10-11 20:51:48

标签: mongodb

我尝试遵循许多线程来解决此问题,但是我无法提出解决方案,也许是因为我是MongoDB的新手。

无论如何,我有2个名为product和product_review的集合,我想在MongoDB中使用Map / Reduce函数将product_review集合中的注释合并到products集合中。公用字段是“名称”。换句话说,我要合并名称下的所有注释,而不必为每个注释重复“名称”字段。

   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.


    ----------
The output that I am looking for is as the following. One Name and or many comments without repeating the name with each comment

{name: “Galaxy Note9”, Price: 900, company: “Samsung”, comment: " Great Product”, comment: " Good”, comment: " I like it”}

我应该提一下,我花了4个小时来遵循此代码,但这是行不通的!

Merging two collections in MongoDB

0 个答案:

没有答案