MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

So verwenden Sie Variablen mit MongoDB $lookup

Wenn Autos und Fahrräder keine gemeinsamen IDs haben, können Sie sequentiell in separaten Arrays suchen und diese dann mit $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,
  }}
]);

Andernfalls müssen Sie $facet verwenden um Fahrzeuge vor der Suche nach Typ zu filtern:

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