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"  
   }]    
}  
0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

@micki but I have another doubt this scenario can you please see group promotional collection and product collection.
@HariSmith have you opened another question ?
@micki no I have changed my question can you please see for group promotional collection and product collection this scenario how to acheive mapping two collections
@micki sorry I wrong edit data .I will correct and updated it.can you please tell me this scenerio how to achieve it.
@micki thanks for your solution this its working fine.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.