【问题标题】:mongodb join multiple collections [duplicate]mongodb加入多个集合[重复]
【发布时间】:2016-11-25 15:02:00
【问题描述】:

我想通过使用 mongochef 在 MongoDB 中“加入”3 个集合。集合是“订单”、“员工”和“城市”。我尝试使用临时集合,但它无效。 现在我使用 var = a 作为第一个“加入”。

如果我想显示“a”,则只显示 20 个结果。 您有什么想法或其他解决方案吗?

        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
    }
}

])

提前感谢您的回复。

【问题讨论】:

    标签: mongodb join mongodb-query lookup var


    【解决方案1】:

    您可以放置​​多个 $lookup 阶段,因此您可以使用这样的查询(无法测试但应该可以) 但是您应该避免多次连接,请记住 MongoDB 不是关系数据库...

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

    【讨论】:

    • $project有什么用?
    猜你喜欢
    • 2018-04-11
    • 2016-12-01
    • 2022-01-01
    • 2020-04-13
    • 2020-03-30
    • 2021-01-16
    • 2020-05-12
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多