如何在 mongoengine 中只包含选定的嵌入式文档?

How to include only selected embedded document in mongoengine?

我正在根据特定 EmbeddedDocument 获取文档,但我不想在检索时获取所有 EmbeddedDocuments,只获取与 main 匹配的 EmbeddedDocument Document.

这是我的代码:

学校内嵌文档

class School(EmbeddedDocument):
    name = StringField(max_length=120)

用户文档

class User(Document):
    first_name = StringField(max_length=60, required=True)
    last_name = StringField(max_length=60)
    schools = EmbeddedDocumentListField(School)

送入文档:

user = User.objects.create(first_name="Rohit", last_name="Khatri")
user.schools = [
    School(name="Auden High School")),
    School(name="Baldwin Boys High School"),
    School(name="Baldwin Girls High School"),
    School(name="Aukamm Elementary School"),
    School(name="Mason-Rice Elementary")
]
user.save()

user = User.objects.create(first_name="ABC", last_name="DEF")
user.schools = [
    School(name="Little Harbor Elementary School")),
    School(name="Aukamm Elementary School"),
    School(name="Mason-Rice Elementary")
]
user.save()

我正在使用此代码检索在 schools 字段中有特定学校的 users

users = User.objects(school__match={"name": "Aukamm Elementary School"})

我只想获取学校字段中 Aukamm Elementary School 的所选学校。

接收

[
    {
        "first_name": "Rohit",
        "last_name": "Khatri",
        "schools": [
            {
                "name": "Auden High School"
            },
            {
                "name": "Baldwin Boys High School"
            },
            {
                "name": "Baldwin Girls High School"
            },
            {
                "name": "Aukamm Elementary School"
            },
            {
                "name": "Mason-Rice Elementary"
            }
        ]
    },
    {
        "first_name": "ABC",
        "last_name": "DEF",
        "schools": [
            {
                "name": "Little Harbor Elementary School"
            },
            {
                "name": "Aukamm Elementary School"
            },
            {
                "name": "Mason-Rice Elementary"
            }
        ]
    }
]

需要输出

[
    {
        "first_name": "Rohit",
        "last_name": "Khatri",
        "schools": [
            {
                "name": "Aukamm Elementary School"
            }
        ]
    },
    {
        "first_name": "ABC",
        "last_name": "DEF",
        "schools": [
            {
                "name": "Aukamm Elementary School"
            }
        ]
    }
]

谢谢

您可以将$filter operator in the aggregate函数用作

users = User.objects(school__match={ "name": "Aukamm Elementary School" }).aggregate(
    { "$project": {
        "first_name": 1,
        "last_name": 1,
        "schools": {
             "$filter": {
                  "input": "$schools",
                  "as": "school",
                  "cond": { "$eq": [ "$$school.name", "Aukamm Elementary School" ] }
             }
        }
    } }
)