यदि कार और बाइक में समान आईडी नहीं है, तो आप क्रमिक रूप से अलग-अलग सरणियों में देख सकते हैं, फिर उन्हें $सेटयूनियन :
db.vehicles.aggregate([
{$lookup: {
from: "cars",
localField: "vehicleId",
foreignField: "_id",
as: "carDetails"
}},
{$lookup: {
from: "bikes",
localField: "vehicleId",
foreignField: "_id",
as: "bikeDetails"
}},
{$project: {
vehicleType: 1,
vehicleId: 1,
vehicleDetails:{$setUnion: [ "$carDetails", "$bikeDetails" ]}
}},
{$project: {
carDetails:0,
bikeDetails:0,
}}
]);
अन्यथा आपको $facet का उपयोग करना होगा लुकअप से पहले प्रकार के अनुसार वाहनों को फ़िल्टर करने के लिए:
db.vehicles.aggregate([
{
$facet: {
"cars": [
{$match: {"vehicleType": "cars"}},
{$lookup: {
from: "cars",
localField: "vehicleId",
foreignField: "_id",
as: "vehicleDetails"
}},
],
"bikes": [
{$match: {"vehicleType": "bikes"}},
{$lookup: {
from: "bikes",
localField: "vehicleId",
foreignField: "_id",
as: "vehicleDetails"
}}
]
}
},
{$project: {all: {$setUnion: ["$cars", "$bikes"]}}},
{$unwind: "$all"},
{$replaceRoot: { newRoot: "$all" }}
])