【问题标题】:How to join two collections based on the _id field in mongodb如何根据mongodb中的_id字段加入两个集合
【发布时间】:2018-01-08 14:18:20
【问题描述】:

我有两个集合,称为订单和项目,如下所示。现在,我正在尝试根据 _id 字段加入这些集合。我们可以在这种情况下使用“$lookup”运算符吗?或者有没有其他方法可以解决这个问题。

db.orders.insert([
   { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
   { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }
])


db.items.insert([
  { "_id" : 1, "item" : "almonds", description: "almond clusters", "instock" : 120 },
  { "_id" : 2, "item" : "bread", description: "raisin and nut bread", "instock" : 80 },
  { "_id" : 3, "item" : "pecans", description: "candied pecans", "instock" : 60 }
])

谁能帮我解决这个问题...

【问题讨论】:

  • 你想根据_id从两个集合中获取记录吗?
  • 是的。我正在尝试根据 _id 字段获取记录

标签: mongodb


【解决方案1】:

试试下面的代码:

db.orders.aggregate([
   {
     $lookup:
       {
         from: "items",
         localField: "_id",
         foreignField: "_id",
         as: "item"
       }
  },
  { $unwind: "$item" },
  {
    $project: {
        "_id": 1,
        "price": 1,
        "quantity": 1,
        "description": "$item.description",
        "instock": "$item.instock"
    }
  }
])

由于您知道将存在一对一的关系,因此您可以展开 $lookup 结果,使每个订单只有一个嵌入项目。然后你可以投影你的结果以获得 JSON 的平面结构。这将为您提供以下形状的结果:

{
    "_id" : 1,
    "price" : 12,
    "quantity" : 2,
    "description" : "almond clusters",
    "instock" : 120
}

【讨论】:

    【解决方案2】:

    试试这个。

    db.orders.aggregate([
    { $lookup:
       {
         from: 'items',
         localField: '_id',
         foreignField: '_id',
         as: 'get_data'
       }
     } 
    
    ]).exec(function(err, res) {
    if (err) throw err;
    console.log(res);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 2020-09-03
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多