3

I'd like to "join" 3 Collections in MongoDB by using mongochef. The collections are "Order", "Employee" and "City". I tried to use temp collections, but it is not effective. Now I am using var = a for the first "join".

If I 'd like to show "a", there are displayed 20 results only. Do you have an idea or another solution?

        var a = db.Order.aggregate([
    { 


      $lookup: 
      {
        from: "City",
        localField: "City Key",
        foreignField: "City Key",
        as: "lsg"
      }
    },
    {
        $unwind: "$lsg"
    },
    {
        $project: 
        {
            "_id":1,
            "Salesperson Key":1,
            "City": "$lsg.City"
        }
    }

    ])

    a;

var b = db.Employee.aggregate([
{ 


  $lookup: 
  {
    from: "a",
    localField: "Employee Key",
    foreignField: "Salesperson Key",
    as: "lsg2"
  }
},
{
    $unwind: "$lsg2"
},
{
    $project: 
    {
        "_id":1,
        "Employee":1
    }
}

])

Thanks in advance for replies.

loenni
  • 33
  • 1
  • 1
  • 3

1 Answers1

8

you can put multiple $lookup stages, so you could use a query like this (could't test it but should work) But you should avoid multiple joins, keep in mind that MongoDB is not a relational database...

db.Order.aggregate([
   {
      $lookup:{
         from:"City",
         localField:"City Key",
         foreignField:"City Key",
         as:"lsg"
      }
   },
   {
      $unwind:"$lsg"
   },
   {
      $lookup:{
         from:"Employee",
         localField:"Salesperson Key",
         foreignField:"Employee Key",
         as:"lsg2"
      }
   },
   {
      $unwind:"$lsg2"
   },
   {
      $project:{
         "_id":1,
         "Employee":1,
         "Salesperson Key":1,
         "City":"$lsg.City"
      }
   }
]);
felix
  • 9,007
  • 7
  • 41
  • 62