Als auto's en fietsen geen gemeenschappelijke ID's hebben, kunt u achtereenvolgens zoeken in afzonderlijke arrays en ze combineren met $setUnion :
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,
}}
]);
Anders moet u $facet gebruiken om voertuigen op type te filteren voordat u ze opzoekt:
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" }}
])