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?
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.
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.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With