Jika mobil dan sepeda tidak memiliki ID yang sama, Anda dapat mencari secara berurutan dalam larik terpisah, lalu menggabungkannya dengan $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,
}}
]);
Jika tidak, Anda harus menggunakan $facet untuk memfilter kendaraan menurut jenisnya sebelum melakukan pencarian:
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" }}
])