mongodb join multiple collections [duplicate]

只愿长相守 提交于 2020-08-25 07:14:00

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/40789057/mongodb-join-multiple-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!