Mongoengine ..反转ListField中的项目

时间:2012-03-03 06:22:43

标签: python django mongodb mongoengine

class Example(Document):
    comments =  ListField(field=EmbeddedDocumentField('Comment'), db_field='z')

class Comment(EmbeddedDocument):
    comment = StringField()
    date = DateTimeField()

如何通过Comment EmbeddedDocument'date反转评论列表字段的结果? 我的错误代码..就像......

Example.objects().order_by('-comments__date')

有没有办法通过embeddedDocument的日期反转ListField? 要么 只是反向列表字段?

2 个答案:

答案 0 :(得分:1)

在mongoDB中,您返回与find语句匹配的项目。所以做一个:

Example.objects().order_by('-comments__date')

您只是按最新评论日期订购Example个对象。查询语言用于匹配,因此不会更改返回列表的结果/顺序。如果您需要确保订单,可以使用SortedListField确保列表在保存时排序。但是,这里有一个可能的竞争条件,因为它设置了整个列表。 $push运算符是最好的,但它意味着注释将是一个堆栈,最旧的将附加到末尾。

在他们自己的集合或mongoDB 2.2中可能需要使用comments的替代模式,聚合框架可用于对评论本身进行排序。

答案 1 :(得分:0)

你应该尝试:

Example.objects().order_by('-comments.date')