Question

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

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

how can I reverse the result of comments listfield by Comment EmbeddedDocument'date? my incorrect code.. is like..

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

Is there a way to reverse ListField by embeddedDocument's date? or just reverse listfield?

Was it helpful?

Solution

In mongoDB you return items matched by the find statement. So Doing an:

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

You are just ordering Example objects by the latest comment date. The query language is for matching so does not change the results / order of the returned list. You could use a SortedListField that ensures a list is sorted on save if you need to ensure order. However, there is a possible race condition here as it sets the whole list. The $push operator is best, but it means comments will be a stack and oldest will be appended to the end.

An alternative schema might be desired with comments in their own collection or in mongoDB 2.2 the aggregation framework could be used to sort the comments themselves.

OTHER TIPS

You should try:

Example.objects().order_by('-comments.date')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top