Reputation: 746
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
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:
$lookup
on the dotted
property of an array (as explained in the above query for Category
collection).Upvotes: 1