我有一个部件集合
{
"_id": {
"$oid": "5c735f7fbc162b1ee5cdacca"
},
"@pno": "10701",
"pname": "When Harry Met Sally",
"qoh": "120",
"price": "19.99",
"level": "30"
}
和订单集合
{
"_id": {
"$oid": "5c735fcebc162b1ee5cdaf1a"
},
"@ono": "1022",
"@takenBy": "1001",
"@customer": "2222",
"receivedDate": "1995-02-13",
"shippedDate": "1995-02-20",
"items": {
"item": [
{
"partNumber": "10601",
"quantity": "1"
},
{
"partNumber": "10701",
"quantity": "1"
}
]
}
}
所以问题是如何通过查询这两个集合来显示每个客户订购的零件名称(pname)(如何将零件中的@pno与订单中的partNumber相匹配)? 谢谢!
答案 0 :(得分:0)
{$unwind:{
path:"$items.item",
preserveNullAndEmptyArrays:true
}},
{
$lookup: {
from: "Parts",
localField: "items.partNumber",
foreignField: "pno",
as: "partsDetails"
}
},
可以将其分组。
答案 1 :(得分:0)
您应该使用查找聚合运算符。 https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
db.getCollection('Parts').aggregate([
{$unwind:"$items.item"},
{
$replaceRoot: { newRoot: { $mergeObjects: [ "$$ROOT","$items.item" ] } }
},
{$lookup:
{
from: "Details",
localField: "partNumber",
foreignField: "@pno",
as: "partTitle"
}
},
{ $project: { items: 0 } },
{
$replaceRoot: {
newRoot: { $mergeObjects: [ "$$ROOT",{$arrayElemAt:["$partTitle",0]} ] }
}
},
{ $project: { partTitle: 0 } },
]);
结果:
{
"_id" : ObjectId("5c735f7fbc162b1ee5cdacca"),
"@ono" : "1022",
"@takenBy" : "1001",
"@customer" : "2222",
"receivedDate" : "1995-02-13",
"shippedDate" : "1995-02-20",
"partNumber" : "10701",
"quantity" : "1",
"@pno" : "10701",
"pname" : "When Harry Met Sally",
"qoh" : "120",
"price" : "19.99",
"level" : "30"
}