gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:18:53 27 4
gpt4 key购买 nike

我正在根据特定的 EmbeddedDocument 获取文档,但我不想在检索时获取所有 EmbeddedDocuments,只获取匹配的 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"})

我只想在 schools 字段中获取选定的学校,即 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 运算符在 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" ] }
}
}
} }
)

关于python - 如何在 mongoengine 中只包含选定的嵌入式文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41300524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com