我会推荐以下系列结构,它将季节数组展开为每个季节的多个文档。
这将帮助您直接插入/更新剧集。
就像是
db.series.insertMany([
{
"title": "Sherlock Holmes",
"nr": 1,
"episodes": [
{
"title": "A Study in Pink",
"nr": 1
},
{
"title": "The Blind Banker",
"nr": 2
}
]
},
{
"title": "Sherlock Holmes",
"nr": 2,
"episodes": [
{
"title": "A Scandal in Belgravia",
"nr": 1
},
{
"title": "The Hounds of Baskerville",
"nr": 2
}
]
}
])
查找查询会做这样的事情
episode: { $in: [ episodes._id1, episodes._id2, ... ] }
从文档
如果该字段包含一个数组,则 $in 运算符选择其字段包含一个数组的文档,该数组包含至少一个与指定数组中的值匹配的元素(例如 , 等)
因此,查找将在匹配时返回所有剧集。然后,您可以过滤以仅保留与您的评论剧集相匹配的内容。
所以查询看起来像
db.review.aggregate([
{
"$lookup": {
"from": "series",
"localField": "episode",
"foreignField": "episodes._id",
"as": "episode_entry"
}
},
{
"$addFields": {
"episode_entry": [
{
"$arrayElemAt": {
"$filter": {
"input": {
"$let": {
"vars": {
"season": {
"$arrayElemAt": [
"$episode_entry",
0
]
}
},
"in": "$$season.episodes"
}
},
"as": "result",
"cond": {
"$eq": [
"$$result._id",
"$episode"
]
}
}
}
},
0
]
}
}
])