好的,因为我没有实际的架构:) ...我将尝试解释一些简单的假设。请仔细阅读以下内容!
首先,您需要一个节目集合,为了使其简洁明了,假设它只有两个字段:_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 以获得清晰的参考。希望对您有所帮助!