我正在尝试输出一个班级(来自班级模型)及其引用的学生-学习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)
如果我指的是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
)