我尝试使用mongodb映射三个集合。我完成了两个集合,但是另一个集合我无法映射如何实现它,任何一个给出示例代码。
group_promotion
[{
"id":1,
"group_name":"latest",
products:[6,7,8]
}]
产品
[{
"id":6,
"produc_namme":"bourbon",
"category_id": 20
}]
类别
[{
"id":20,
"category_name":"beer"
}]
映射代码
db.group_promoton.aggregate([{$lookup :
{
from:"product",
localfield:"products",
foreignField:'id',
as:products
}}])
我得到了输出
[{
"id":1,
"group_name":"latest",
products:[{
"id":6,
"produc_namme":"bourbon",
"category_id": 20
}]
}]
例外的输出
[{
"id":1,
"group_name":"latest",
products:[{
"id":6,
"produc_namme":"bourbon",
"category_nmae":"beer"
}]
}]
答案 0 :(得分:1)
在此尝试以下查询:
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"
}
}
}
}
])
注意:
$lookup
属性上使用dotted
(如上面对Category
集合的查询中所述 )。