BaseDocument

class BaseDocument(**kwargs)

The BaseDocument is used to create new Documents which can be used to model your data structures.

Simple example using a StringField and an IntField:

class ExampleDocument(BaseDocument):
    name = StringField(default='myname')
    number = IntField(default=0)

When instantiating a Document object it is possible to use keyword arguments to initialise its fields to the given values.

>>> doc = ExampleDocument(name='Changed My Name', number=15)
>>> print(doc)
<ExampleDocument name='Changed My Name' number=15>
>>> await doc.save()
>>> print(doc)
<ExampleDocument id=ObjectId('$oid') name='Changed My Name' number=15>
Raises:FieldNotFound – On access of a non-existent field

Caution

The id field is reserved and will be set after a successful save. The field has the same properties as when using an ObjectIdField. Will raise an exception if the field is set regardless.

classmethod await get_object(**kwargs)

A find_one wrapper for get_objects(). Queries the collection for a single document. Will return None if there is no or more than one document.

classmethod await get_objects(**kwargs)

Queries the collection for multiple objects as defined by the supplied filters. For querying Motorturbine supplies its own functionality in form of QueryOperator.

await get_reference(field_name, collections=None)

When using ReferenceField this method allows loading the reference by the fields name. Returns None if the given field exists but is not a ReferenceField type.

Parameters:
  • field_name (str) – The name of the ReferenceField
  • collections (list) – optional (None) – A list of BaseDocument classes. In case you allowed subclassing in a ReferenceField you can specify the additional document collections that will be searched if they are not the same as the specified documents type.
Raises:

FieldNotFound – On access of a non-existent field

await save(limit=0)

Calling the save method will start a synchronisation process with the database. Every change that was made since the last synchronisation is considered specifically to only update based on the condition that no fields that changed were updated in the meantime. In case that any conflicting fields did update we make sure to pull these changes first and only then update them to avoid critical write errors.

If a document has not been saved before the ‘id’ field will be set automatically after the update is done.

Parameters:limit (int) – optional (0) – The maximum amount of tries before a save operation fails. Can be used as a way to catch problematic state or to probe if the current document has changed yet if set to 1.
Raises:RetryLimitReached – Raised if limit is reached
to_json()

Returns the entire document as a json dictionary.