嵌套关系 MongoDb [英] Nested Relations MongoDb
问题描述
我需要一些帮助.我有 2 个要关联的 MongoDB 集合.一种用于类别,另一种用于多媒体内容.一个类别可以包含一个多媒体内容和多个 Childs 类别.
通过传递管道执行聚合后,我得到返回格式(见图 1):Category.Media 内的媒体元素和 Category.Childs 内的子类别.我的问题是我不知道如何在子类别中再次插入媒体(见图 2)
我也离开了使用过的管道.
返回结果:
预期结果:
管道:
<预><代码>[{$匹配":{id_site":3,id_parent":空,id_class":空}},{$查找":{"from": "类别","localField": "_id","foreignField": "id_parent","as": "孩子们"}},{$查找":{"from": "媒体","localField": "id_media","foreignField": "_id","as": "媒体"}}]提前致谢.任何建议表示赞赏.
您必须修改第一个 $lookup
以使用 管道(可从 v3.6 获得)
I need some help. I have 2 MongoDB collections that I want to relate. One is for categories and the other for multimedia content. A category can contain one multimedia content and Many Childs Categories.
After execute aggregation by passing the pipeline I get the Returned Format (See image 1): Media elements inside Category.Media and Child categories inside Category.Childs. My problem is that I don't know how I can insert again Media inside Child Categories (See image 2)
I also leave below the used pipeline.
Returned Result:
Expected Result:
The Pipeline:
[
{
"$match": {
"id_site": 3,
"id_parent": null,
"id_class": null
}
},
{
"$lookup": {
"from": "categories",
"localField": "_id",
"foreignField": "id_parent",
"as": "Childs"
}
},
{
"$lookup": {
"from": "media",
"localField": "id_media",
"foreignField": "_id",
"as": "Media"
}
}
]
Thanks in advance. Any suggestion is appreciated.
You'll have to modify the first $lookup
to use a pipeline (available from v3.6)
[
{
"$match": {
"id_site": 3,
"id_parent": null,
"id_class": null
}
},
{
"$lookup": {
"from": "categories",
"let": {
"cid": "$_id"
},
"pipeline": [
{
"$match": {
"$expr": { $eq: ["$id_parent", "$$cid"] }
}
},
{
"$lookup": {
"from": "media",
"localField": "id_media",
"foreignField": "_id",
"as": "Media"
}
}
],
"as": "Childs"
}
},
{
"$lookup": {
"from": "media",
"localField": "id_media",
"foreignField": "_id",
"as": "Media"
}
}
]
这篇关于嵌套关系 MongoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!