Mongoengine: How to sort Embedded Document list by Embedded document field

我怕爱的太早我们不能终老 提交于 2019-11-29 22:24:22

问题


So what I'm after is something like:

class Comment(EmbeddedDocument):
    content = StringField()
    upvotes = IntField()
    pub_date = DateTimeField()

class Post(Document):
    title = StringField()
    comments = SortedListField(EmbeddedDocumentField(Comment))
    post_date = DateTimeField()

By default, this sorts by the chronological order of comment submission, but I want to make the SortedListField sort by the upvotes attribute of the embedded comment documents. Is this possible, and if so how do I go about it?


回答1:


This is actually covered in the unit tests if not clear from the documentation itself:

class Post(Document):
    title = StringField()
    comments = SortedListField(EmbeddedDocumentField(Comment)
                               ordering="upvotes", reverse=True)
    post_date = DateTimeField()

So adding the "ordering" keyword allows the field to sort on when the items are changed to be specified. You probably also want the reverse statement to make sure the highest "upvotes" value is first as well.

The unit tests actually show some other usages as well so are always a good source for finding out possibly obscure usages.



来源:https://stackoverflow.com/questions/22997738/mongoengine-how-to-sort-embedded-document-list-by-embedded-document-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!