hari prasanth
hari prasanth

Reputation: 746

How to map three collection using mongodb

I tried to map three collection using mongodb .I completed two collection but another collection I cant map how to achieve it any one give example code.

group_promotion

[{

"id":1,
"group_name":"latest",  
 products:[6,7,8]

}]

product

[{

"id":6,  
"produc_namme":"bourbon",
"category_id": 20

}]

Category

[{

"id":20,
"category_name":"beer"

}]

Mapping code

db.group_promoton.aggregate([{$lookup :  
{  
from:"product",  
localfield:"products",  
foreignField:'id',  
as:products  
}}])

I got output

[{

"id":1,
"group_name":"latest",  
 products:[{
"id":6,  
"produc_namme":"bourbon",
"category_id": 20
}]

}]

Excepted output

[{

"id":1,  
"group_name":"latest",    
 products:[{  
"id":6,    
"produc_namme":"bourbon",  
"category_nmae":"beer"  
}]

}]

Upvotes: 0

Views: 91

Answers (1)

vikscool
vikscool

Reputation: 1313

Here give the below query a try:

db.getCollection("group_promotion").aggregate([
{
    $lookup: {
        from: "product",
        localField: "products",
        foreignField: "id",
        as: "products"
    }
},
{ $unwind: "$products" },
{
    $lookup: {
        from: "Category",
        localField: "products.category_id",
        foreignField: "id",
        as: "category"
    }
},
{ $unwind: "$category" },
{
    $group: {
        _id: '$id', "group_name": { $first: "$group_name" }, "products": {
            $push: {
                "id": "$products.id", "produc_namme": "$products.produc_namme", "category_nmae": "$category.category_name"
            }
        }
    }
}
])

Note:

  • You can always use $lookup on the dotted property of an array (as explained in the above query for Category collection).
  • Here i am using $unwind to deconstruct the arrays (i.e. products and category) and later grouping them to create the result. I have used $first to satisfy the $group accumulators policy and display the first value.

Upvotes: 1

Related Questions