如何在MongoEngine中引用一对多-在模式和聚合输出中(新手)

2024-05-13 20:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图输出一个类(从类模型)及其引用的学生——学习mongoengine和mongodb。下面的代码给出了错误

Expected 'pipeline' to be BSON docs (or equivalent), but got []

我相信这是显而易见的——对于那些了解mongo和mongoengine的人来说。任何帮助(或推动正确的方向)都是非常感谢的:)提前谢谢

import urllib
from mongoengine import *


connect(db=DB_NAME, username=DB_USER, password=DB_PASSWORD,
        host=DB_URI)

class Students(Document):
    student_id = IntField(unique=True)  
    name = StringField(max_length=50)
    age = IntField(max_length=2)
    gender = StringField(choices=('male', 'female'))


class Classes(Document):
    class_id = IntField(required=True, unique=True)  # 1576407600000
    student_roster = ListField(ReferenceField(Students))


Students.objects.insert([
    Students(name="John", student_id=425736, age=10, gender="male"),
    Students(name="Mary", student_id=114391, age=9, gender="female")
])

Classes(class_id=1576407600000, student_roster=[425736, 114391]).save()


# gives pipeline error
c = Classes.objects.aggregate([
    {'$lookup': {'from': 'students',
            'localField' : 'student_roster',
            'foreignField' : 'student_id',
            'as': 'studentData'
    }
}
])
list(c)

Tags: nameimportidtruedbagepipelinegender
1条回答
网友
1楼 · 发布于 2024-05-13 20:34:09

如果我提到the docs

class Person(Document):
    name = StringField()

Person(name='John').save()
Person(name='Bob').save()

pipeline = [
    {"$sort" : {"name" : -1}},
    {"$project": {"_id": 0, "name": {"$toUpper": "$name"}}}
    ]
data = Person.objects().aggregate(*pipeline)
assert data == [{'name': 'BOB'}, {'name': 'JOHN'}]

您正在使用objects成员而不是objects()成员,并且您正在传递一个list,它希望它被解压到dict参数中(在*pipeline,您在这里放置了pipeline的等价物)

相关问题 更多 >