MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come utilizzare le variabili con MongoDB $lookup

Se auto e biciclette non hanno ID comuni, puoi cercare in sequenza in array separati, quindi combinarli con $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,
  }}
]);

Altrimenti dovrai usare $facet per filtrare i veicoli per tipo prima della ricerca:

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" }}
])