Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 763
jvc26 Avatar asked Apr 10 '14 19:04

jvc26


People also ask

What is a document in mongoengine?

Defining documents — MongoEngine 0.23.1 documentation 2.3. Defining documents ¶ In MongoDB, a document is roughly equivalent to a row in an RDBMS. When working with relational databases, rows are stored in tables, which have a strict schema that the rows follow.

How do I work with existing data in mongoengine?

Working with existing data ¶ As MongoEngine no longer defaults to needing _cls, you can quickly and easily get working with existing data. Just define the document to match the expected schema in your database If you have wildly varying schemas then using a DynamicDocument might be more appropriate, instead of defining all possible field types.

How do I define schemata for documents in mongoengine?

MongoEngine allows you to define schemata for documents as this helps to reduce coding errors, and allows for utility methods to be defined on fields which may be present. To define a schema for a document, create a class that inherits from Document. Fields are specified by adding field objects as class attributes to the document class:

How do I make a field unique in mongoengine?

MongoEngine allows you to specify that a field should be unique across a collection by providing unique=True to a Field‘s constructor. If you try to save a document that has the same value for a unique field as a document that is already in the database, a NotUniqueError will be raised.


1 Answers

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.

like image 138
Neil Lunn Avatar answered Oct 11 '22 16:10

Neil Lunn