【问题标题】:Mongoengine.. reverse the items in ListFieldMongoengine.. 反转 ListField 中的项目
【发布时间】:2012-03-03 06:22:43
【问题描述】:
class Example(Document):
    comments =  ListField(field=EmbeddedDocumentField('Comment'), db_field='z')

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

如何通过 Comment EmbeddedDocument'date 反转 cmets listfield 的结果? 我不正确的代码..就像..

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

有没有办法通过 EmbeddedDocument 的日期来反转 ListField? 或者 只是反向列表字段?

【问题讨论】:

    标签: python django mongodb mongoengine


    【解决方案1】:

    在 mongoDB 中,您返回与 find 语句匹配的项目。这样做:

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

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

    comments 在他们自己的集合中或在 mongoDB 2.2 中可能需要一个替代架构,聚合框架可用于对 cme​​ts 本身进行排序。

    【讨论】:

      【解决方案2】:

      你应该试试:

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

      【讨论】:

        猜你喜欢
        • 2016-05-18
        • 2014-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多