【问题标题】:Joins - Mongodb连接 - Mongodb
【发布时间】:2019-03-20 11:55:21
【问题描述】:

我正在尝试加入两个集合。我的第一个集合有一个字符串字段,其中包含第二个集合中文档的 id。像这样:

coll A:
{ show_id: "5c5bf36bfb6fc06f4f57930c"}

coll B:
{ _id: { $oid: "5c5bf36bfb6fc06f4f57930c" } }

我无法提出正确的 $lookup。请帮忙。

【问题讨论】:

  • 您能否提供代码 sn-p 以及您打算对这些集合执行什么操作?
  • 我正在尝试开发一个电影票预订应用程序。在那个 'bookings' 集合中,电影节目 id 需要与 'shows' 集合一起加入。同时显示已预订的门票历史预订收藏和演出收藏需要加入。

标签: mongodb


【解决方案1】:

好的,因为我没有实际的架构:) ...我将尝试解释一些简单的假设。请仔细阅读以下内容!

首先,您需要一个节目集合,为了使其简洁明了,假设它只有两个字段:_id(标识符)和 showTime..(更好)

其次,您需要一个电影集合,假设它有 3 个字段:_id(标识符)、标题和 [showID](showID 是引用节目集合的 objectID 数组)

第三,bookings 集合,所以它应该有:_id、movieID(特定电影文档的 objectID)和 showID(特定放映文档的 ojectID)。

因此,您的模型将是:

bookings{
_id,
movieID,
showID
}

movies{
_id,
title,
[showID]
}

shows{
_id,
showTime
}

这是 mongodb 中的示例模拟数据:

 //shows collection
{
  _id: 1
  showTime:"3 PM"
}

{
  _id: 2
  showTime:"6 PM"
}


//movies collection
{
  _id: 1
  title:"Matrix"
  showID:[1,2]
}

{
  _id: 2
  title:"John Wick"
  showID:[1,2]
}

//bookings collection
{
  _id:1
  movieID:1
  showID:1
}  


{
  _id:2
  movieID:1
  showID:2
}

{
  _id:3
  movieID:2
  showID:2
}

因此,假设您想查看特定的预订历史记录,那么您可以执行以下代码来查看预订、电影和节目之间的关系(连接):

db.bookings.aggregate([

    // Join with shows collection
    {
        $lookup:{
            from: "shows",       // shows collection
            localField: "showID",   // field name of bookings collection
            foreignField: "_id", // field name of show collection
            as: "shows_info"         // alias for show collection
        }
    },
    {   $unwind:"$shows_info" },     // $unwind used for getting data in object or for one record only

    // Join with movies collection
    {
        $lookup:{
            from: "movies", 
            localField: "movieID", 
            foreignField: "_id",
            as: "movies_info"
        }
    },
    {   $unwind:"$movies_info" },

    // query for your matching condition here, for example in this case, it would be _id of bookings collection
    {
        $match:{
            $and:[{"_id" : 1}] // here if you replace 1 with 2, you would get data of booking id 2 and so on...
        }
    },

    // define which fields you want to fetch
    {   
        $project:{
            _id : 1,
            movieID : 1, // field of bookings collection
            showID : 1, // field of bookings collection
            movieTitle : "$movies_info.title",// field of movies collection
            showTime : "$shows_info.showTime",// field of shows collection
        } 
    }
]);

以下是一些结果输出:

我希望这可以解决您的问题...恕我直言,如果您也执行数据建模以更好地了解您处理集合的方式会更好,请查看mongoose。如果您想详细了解 $unwind 和 $lookup 以这种方式使用的方式和原因,请查看 mongodb 的官方文档,或者您甚至可以查看 question 以获得清晰的参考。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多