如何在单个 mongo 集合中过滤父数据集后获取子数据?
How to get Child data after filtering dataset of Parents in a single mongo collection?
我有一个名为“CourseCollection”的 mongo 集合,它包含父文档和子文档。任何带有键“Parent”的文档都是一个子文档,一个父文档可以有多个子文档。
{
"_id" : "abracadavra",
"Name" : "abracadavra",
"Description" : "",
"Type" : "Spell",
"Parent" : {
"_id" : "Magic",
"Type" : "Course",
"Name" : "Magic"
}
},
{
"_id" : "Magic",
"Name" : "Magic",
"Type" : "Course",
"Access" : [
{
"_id" : "2sssdw5oe",
"Name" : "Abc"
},
{
"_id" : "4fddfye42",
"Name" : "Xyz"
}
]
}
我想做的是,基于父文档的访问权限,我正在尝试获取所有子文档。
现有和有效的解决方案:
我目前的解决方案是执行2次查询。
查询1.获取用户有权访问的所有课程。
db.getCollection("CourseCollection").find({"Type": "Course", "Access._id": {"$in": ["2sssdw5oe"]}})
查询 2。由于我使用的是 Python,因此我进行了列表理解以仅获取课程的 ID,然后使用此列表执行另一个查询
db.getCollection("CourseCollection").find({"Type": "Spell", "Parent._id": {"$in": course_list_id}})
有没有办法在单个查询中过滤掉父数据后获取子数据。我也尝试过聚合,但只有前一阶段的结果被传递到下一阶段。
我猜你正试图做这样的事情:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents"
}
},
{
"$match": {
"Parents": {
"$elemMatch": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
}
}
])
你也可以这样做得到同样的结果:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents",
"pipeline": [
{
"$match": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
]
}
},
{
"$match": {
"Parents.0": {
"$exists": true
}
}
}
])
我有一个名为“CourseCollection”的 mongo 集合,它包含父文档和子文档。任何带有键“Parent”的文档都是一个子文档,一个父文档可以有多个子文档。
{
"_id" : "abracadavra",
"Name" : "abracadavra",
"Description" : "",
"Type" : "Spell",
"Parent" : {
"_id" : "Magic",
"Type" : "Course",
"Name" : "Magic"
}
},
{
"_id" : "Magic",
"Name" : "Magic",
"Type" : "Course",
"Access" : [
{
"_id" : "2sssdw5oe",
"Name" : "Abc"
},
{
"_id" : "4fddfye42",
"Name" : "Xyz"
}
]
}
我想做的是,基于父文档的访问权限,我正在尝试获取所有子文档。
现有和有效的解决方案:
我目前的解决方案是执行2次查询。
查询1.获取用户有权访问的所有课程。
db.getCollection("CourseCollection").find({"Type": "Course", "Access._id": {"$in": ["2sssdw5oe"]}})
查询 2。由于我使用的是 Python,因此我进行了列表理解以仅获取课程的 ID,然后使用此列表执行另一个查询
db.getCollection("CourseCollection").find({"Type": "Spell", "Parent._id": {"$in": course_list_id}})
有没有办法在单个查询中过滤掉父数据后获取子数据。我也尝试过聚合,但只有前一阶段的结果被传递到下一阶段。
我猜你正试图做这样的事情:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents"
}
},
{
"$match": {
"Parents": {
"$elemMatch": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
}
}
])
你也可以这样做得到同样的结果:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents",
"pipeline": [
{
"$match": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
]
}
},
{
"$match": {
"Parents.0": {
"$exists": true
}
}
}
])