簡體   English   中英

如何在 MongoEngine 中引用一對多——在模式和聚合輸出中(新手)

[英]How to Reference One to Many in MongoEngine––in the Schema and Aggregate output (Newbie)

我正在嘗試輸出一個類(來自類模型)及其引用的學生——以學習 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)

如果我參考文檔

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM