2

I have doubt how to map two collection in mongodb using mongoclient.I tried it but its not working.how to solve it

group_promotion collection

{ 
    "_id" : ObjectId("5cf7679a0b0bed2e7483b998"), 
    "group_name" : "Latest", 
    "products" : [ObjectId("5cecc161e8c1e73478956333"),ObjectId("5cecc161e8c1e73478956334")]  
}

product collection

{ 
    "_id" : ObjectId("5cecc161e8c1e73478956333"), 
    "product_name" : "bourbon"
},
{ 
    "_id" : ObjectId("5cecc161e8c1e73478956334"), 
    "product_name" : "bour"
}

Expected output:

{   
    "_id" : ObjectId("5cf7679a0b0bed2e7483b998"),   
    "group_name" : "Latest",   
    "products" : [{   
    "_id" : ObjectId("5cecc161e8c1e73478956333"),   
    "product_name" : "bourbon"  
    },{
   "_id" : ObjectId("5cecc161e8c1e73478956334"),   
    "product_name" : "bour"  
   }]    
}  
Hari Smith
  • 143
  • 1
  • 9

1 Answers1

3

You can run $lookup directly on products array to get expected result:

db.group_promotion.aggregate([
    {
        $lookup: {
            from: "product",
            localField: "products",
            foreignField: "_id",
            as: "products"
        }
    }
])

This will take products from an array, find corresponding documents in products collection an overwrite exisiting products array in group_production

mickl
  • 48,568
  • 9
  • 60
  • 89