我在特定EmbeddedDocument
的基础上提取文档,但我不希望在检索时获取所有EmbeddedDocuments
,只检索匹配的EmbeddedDocument
与主Document
1}}。
这是我的代码:
学校嵌入式文件
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()
我正在使用此代码检索users
字段中包含特定学校的schools
:
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"
}
]
}
]
由于
答案 0 :(得分:2)
您可以在 $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" ] }
}
}
} }
)