1

I have an Express API, and I'm trying to get everything from multiple collections. I believe that aggregation is probably the way to go, but I'm having a hard time getting my head around aggregation, and am under the impression that you need to specify each of the keys you want. However, in another example with data with a large number of keys, the aggregation query could become rather large.

A simple example:

Cars

{
 Name: 'A',
 Type: 'Car',
 Tyres: 'B'
}

Bike

{
 Name: 'B',
 Type: 'Bike',
 Tyres: 'C'
}

Truck

{
 Name: 'C',
 Type: 'Truck',
 Tyres: 'D',
 Size: 'E',
}

I would like to do a GET request where I can get everything from these collections, currently I am using a loop but I feel like there's probably a better way of doing it.

Edit: I would like the result to be something like this

{
    {
         Name: 'A',
         Type: 'Car',
         Tyres: 'C',
    },
    {
         Name: 'B',
         Type: 'Bike',
         Tyres: 'C',
    },
    {
         Name: 'C',
         Type: 'Truck',
         Tyres: 'D',
         Size: 'E',
    }
}
Dillon
  • 21
  • 2

1 Answers1

0

You Can follow This code

db.Cars.aggregate([

    {
        $lookup:{
            from:'Bike',
            localField:'Name',
            foreignField:'Name',
            as:'bikeInfo'

        }},

         { 
               $unwind:"$bikeInfo" 
          },


       { $lookup:{
            from:'Truck',
            localField:'Name',
            foreignField:'Name',
            as:'truck_info'


        }},

        {$unwind:"$truck_info" }


])
Shuvro
  • 222
  • 3
  • 7