python - Mongoengine:如何按嵌入式文档字段对嵌入式文档列表进行排序

标签 python mongodb mongoengine

所以我想要的是这样的:

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

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

默认情况下,这是按评论提交的时间顺序排序的,但我想让 SortedListField 按嵌入评论文档的 upvotes 属性排序。这可能吗?如果可以,我该怎么做?

最佳答案

这实际上已在 unit tests 中进行了介绍。如果不清楚 documentation本身:

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

因此,添加“ordering”关键字允许字段在更改指定项目时进行排序。您可能还希望反向语句确保最高的“upvotes”值也排在第一位。

单元测试实际上也显示了一些其他用法,因此始终是找出可能晦涩的用法的好来源。

关于python - Mongoengine:如何按嵌入式文档字段对嵌入式文档列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22997738/

相关文章:

python - 循环excel文件并基于Python中的一个公共(public)列进行合并

json - 如何查询 MongoDB 集合上的日期范围,其中 ISO 日期存储在字符串字段中?

python - MongoEngine 是否准备好使用多语言字符串字段?

java - 如何在 mongodb 中使用 where 条件从集合中获取不同的值?

mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据

python - 过滤 mongoengine 查询

python - 使用 mongenine 切换数据库

Python Popen shell=False 导致 OSError : [Errno 2] No such file or directory FFREPORT

python - 类型错误 : '>=' not supported between instances of 'int' and 'str' even with adding int to the front of score

python - 来自 archive.ics 的 "Adult data set"(数据集)上的 ML...使用 KNeighborsClassifier 将无法运行