0

I tried to follow many threads to solve this, but I couldn't come up with a solution, maybe because I am new to MongoDB.

Anyway, I have 2 collections named products and product_review, and I would like to use Map/Reduce function in MongoDB to merge the comment from product_review collection to products collection. The common field is "name". In other words, I want to merge all comment under the name without repeating the "Name" field for each comment.

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

I should mention that I spent 4 hours to follow this code, but It does not work!

Merging two collections in MongoDB

Fahed
  • 11
  • 1

0 Answers0