mongomotor package¶
Submodules¶
mongomotor.clients module¶
- class mongomotor.clients.DummyMongoMotorTornadoClient(*args, **kwargs)[source]¶
Bases:
object
A dummy class to raise an exception when creating an instance warning about the absense of tornado.
- mongomotor.clients.MongoMotorAsyncIOClient¶
alias of
AsyncIOMongoMotorClient
- mongomotor.clients.MongoMotorTornadoClient¶
alias of
MongoMotorClient
mongomotor.connection module¶
- mongomotor.connection.connect(db=None, async_framework='asyncio', alias='default', **kwargs)[source]¶
Connect to the database specified by the ‘db’ argument.
Connection settings may be provided here as well if the database is not running on the default port on localhost. If authentication is needed, provide username and password arguments as well.
Multiple databases are supported by using aliases. Provide a separate alias to connect to a different instance of mongod.
Parameters are the same as for
mongoengine.connection.connect()
plus one:- Parameters:
async_framework – Which asynchronous framework should be used. It can be tornado or asyncio. Defaults to asyncio.
- mongomotor.connection.disconnect(alias='default')[source]¶
Disconnects from the database indentified by
alias
.
mongomotor.core module¶
- class mongomotor.core.MongoMotorAgnosticClient(*args, **kwargs)[source]¶
Bases:
MongoMotorAgnosticClientBase
,AgnosticClient
- class mongomotor.core.MongoMotorAgnosticCollection(database, name, _delegate=None)[source]¶
Bases:
AgnosticCollection
- find(*args, **kwargs)[source]¶
Create a
MongoMotorAgnosticCursor
. Same parameters as for PyMongo’sfind()
.Note that
find
does not take a callback parameter, nor does it return a Future, becausefind
merely creates aMongoMotorAgnosticCursor
without performing any operations on the server.MongoMotorAgnosticCursor
methods such asto_list()
orcount()
perform actual operations.
- find_one = <mongomotor.metaprogramming.OriginalDelegate object>¶
- find_one_and_delete = <mongomotor.metaprogramming.OriginalDelegate object>¶
- find_one_and_update = <mongomotor.metaprogramming.OriginalDelegate object>¶
- index_information = <mongomotor.metaprogramming.OriginalDelegate object>¶
- insert_many = <mongomotor.metaprogramming.OriginalDelegate object>¶
- insert_one = <mongomotor.metaprogramming.OriginalDelegate object>¶
- update_many = <mongomotor.metaprogramming.OriginalDelegate object>¶
- update_one = <mongomotor.metaprogramming.OriginalDelegate object>¶
mongomotor.decorators module¶
- mongomotor.decorators.aiter_compat(func)¶
mongomotor.dereference module¶
mongomotor.document module¶
- class mongomotor.document.Document(*args, **kwargs)[source]¶
Bases:
NoDerefInitMixin
,Document
- The base class used for defining the structure and properties of
collections of documents stored in MongoDB. Inherit from this class, and add fields as class attributes to define a document’s structure. Individual documents may then be created by making instances of the
Document
subclass.By default, the MongoDB collection used to store documents created using a
Document
subclass will be the name of the subclass converted to lowercase. A different collection may be specified by providingcollection
to themeta
dictionary in the class definition.A
Document
subclass may be itself subclassed, to create a specialised version of the document that will be stored in the same collection. To facilitate this behaviour a _cls field is added to documents (hidden though the MongoEngine interface). To disable this behaviour and remove the dependence on the presence of _cls setallow_inheritance
toFalse
in themeta
dictionary.A
Document
may use a Capped Collection by specifyingmax_documents
andmax_size
in themeta
dictionary.max_documents
is the maximum number of documents that is allowed to be stored in the collection, andmax_size
is the maximum size of the collection in bytes.max_size
is rounded up to the next multiple of 256 by MongoDB internally and mongoengine before. Use also a multiple of 256 to avoid confusions. Ifmax_size
is not specified andmax_documents
is,max_size
defaults to 10485760 bytes (10MB).Indexes may be created by specifying
indexes
in themeta
dictionary. The value should be a list of field names or tuples of field names. Index direction may be specified by prefixing the field names with a + or - sign.Automatic index creation can be enabled by specifying
auto_create_index
in themeta
dictionary. If this is set to True then indexes will be created by MongoMotor.By default, _cls will be added to the start of every index (that doesn’t contain a list) if allow_inheritance is True. This can be disabled by either setting cls to False on the specific index or by setting index_cls to False on the meta dictionary for the document.
- By default, any extra attribute existing in stored data but not declared
in your model will raise a
mongoengine.FieldDoesNotExist
error. This can be disabled by settingstrict
toFalse
in themeta
dictionary.
- classmethod compare_indexes()[source]¶
Compares the indexes defined in MongoEngine with the ones existing in the database. Returns any missing/extra indexes.
- async delete(signal_kwargs=None, **write_concern)[source]¶
Delete the
Document
from the database. This will only take effect if the document has been previously saved.- Parm signal_kwargs:
(optional) kwargs dictionary to be passed to the signal calls.
- Parameters:
write_concern – Extra keyword arguments are passed down which will be used as options for the resultant
getLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.
- classmethod drop_collection()[source]¶
Drops the entire collection associated with this
mongomotor.Document
type from the database.
- classmethod ensure_indexes()[source]¶
Checks the document meta data and ensures all the indexes exist.
Global defaults can be set in the meta - see guide/defining-documents
By default, this will get called automatically upon first interaction with the Document collection (query, save, etc) so unless you disabled auto_create_index, you shouldn’t have to call this manually.
This also gets called upon every call to Document.save if auto_create_index_on_save is set to True
If called multiple times, MongoDB will not re-recreate indexes if they exist already
Note
You can disable automatic index creation by setting auto_create_index to False in the documents meta data
- modify(query={}, **update)[source]¶
Perform an atomic update of the document in the database and reload the document object using updated version.
Returns True if the document has been updated or False if the document in the database doesn’t match the query.
Note
All unsaved changes that have been made to the document are rejected if the method returns True.
- Parameters:
query – the update will be performed only if the document in the database matches the query
update – Django-style update keyword arguments
- classmethod register_delete_rule(document_cls, field_name, rule)[source]¶
This method registers the delete rules to apply when removing this object.
- coroutine reload(*fields, **kwargs)[source]¶
Reloads all attributes from the database.
- Parameters:
fields – (optional) args list of fields to reload
max_depth – (optional) depth of dereferencing to follow
- coroutine save(force_insert=False, validate=True, clean=True, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, save_condition=None, signal_kwargs=None, **kwargs)[source]¶
Save the
Document
to the database. If the document already exists, it will be updated, otherwise it will be created. Returns the saved object instance.- Parameters:
force_insert – only try to create a new document, don’t allow updates of existing documents.
validate – validates the document; set to
False
to skip.clean – call the document clean method, requires validate to be True.
write_concern – Extra keyword arguments are passed down to
save()
ORinsert()
which will be used as options for the resultantgetLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.cascade – Sets the flag for cascading saves. You can set a default by setting “cascade” in the document __meta__
cascade_kwargs – (optional) kwargs dictionary to be passed throw to cascading saves. Implies
cascade=True
._refs – A list of processed references used in cascading saves
save_condition – only perform save if matching record in db satisfies condition(s) (e.g. version number). Raises
OperationError
if the conditions are not satisfiedsignal_kwargs – (optional) kwargs dictionary to be passed to the signal calls.
- class mongomotor.document.DynamicDocument(*args, **kwargs)[source]¶
Bases:
Document
,DynamicDocument
- class mongomotor.document.EmbeddedDocument(*args, **kwargs)[source]¶
Bases:
NoDerefInitMixin
,EmbeddedDocument
mongomotor.exceptions module¶
mongomotor.fields module¶
- class mongomotor.fields.BaseAsyncReferenceField[source]¶
Bases:
object
Base class to asynchronize reference fields.
- class mongomotor.fields.DictField(field=None, *args, **kwargs)[source]¶
Bases:
ComplexBaseField
,DictField
- class mongomotor.fields.FileField(db_alias='default', collection_name='fs', **kwargs)[source]¶
Bases:
FileField
- proxy_class¶
alias of
GridFSProxy
- class mongomotor.fields.GenericReferenceField(*args, **kwargs)[source]¶
Bases:
BaseAsyncReferenceField
,GenericReferenceField
- class mongomotor.fields.GridFSProxy(*args, **kwargs)[source]¶
Bases:
GridFSProxy
- property fs¶
- new_file(**metadata)[source]¶
Opens a new stream for writing to gridfs.
- Parameters:
metadata – File’s metadata.
- async put(data, **metadata)[source]¶
Writes
data
to gridfs.- Parameters:
data – byte-string to write.
metatada – File’s metadata.
- class mongomotor.fields.ListField(field=None, max_length=None, **kwargs)[source]¶
Bases:
ComplexBaseField
,ListField
- class mongomotor.fields.ReferenceField(document_type, dbref=False, reverse_delete_rule=0, **kwargs)[source]¶
Bases:
BaseAsyncReferenceField
,ReferenceField
A reference to a document that will be automatically dereferenced on access (lazily).
Use the reverse_delete_rule to handle what should happen if the document the field is referencing is deleted. EmbeddedDocuments, DictFields and MapFields does not support reverse_delete_rule and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.
The options are:
DO_NOTHING (0) - don’t do anything (default).
NULLIFY (1) - Updates the reference to null.
CASCADE (2) - Deletes the documents associated with the reference.
DENY (3) - Prevent the deletion of the reference object.
PULL (4) - Pull the reference from a
ListField
of references
Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)
class Bar(Document): content = StringField() foo = ReferenceField('Foo') Foo.register_delete_rule(Bar, 'foo', NULLIFY)
mongomotor.gridfs module¶
- class mongomotor.gridfs.MongoMotorAgnosticGridFS(database, collection='fs')[source]¶
Bases:
AgnosticGridFSBucket
Create a handle to a GridFS bucket.
Raises
ConfigurationError
if write_concern is not acknowledged.This class conforms to the GridFS API Spec for MongoDB drivers.
- Parameters:
database: database to use.
bucket_name (optional): The name of the bucket. Defaults to ‘fs’.
chunk_size_bytes (optional): The chunk size in bytes. Defaults to 255KB.
write_concern (optional): The
WriteConcern
to use. IfNone
(the default) db.write_concern is used.read_preference (optional): The read preference to use. If
None
(the default) db.read_preference is used.disable_md5 (optional): When True, MD5 checksums will not be computed for uploaded files. Useful in environments where MD5 cannot be used for regulatory or other reasons. Defaults to False.
- class mongomotor.gridfs.MongoMotorAgnosticGridIn(root_collection, delegate=None, **kwargs)[source]¶
Bases:
AgnosticGridIn
- class mongomotor.gridfs.MongoMotorAgnosticGridOut(root_collection, file_id=None, file_document=None, delegate=None)[source]¶
Bases:
AgnosticGridOut
Class to read data out of GridFS.
MotorGridOut supports the same attributes as PyMongo’s
GridOut
, such as_id
,content_type
, etc.You don’t need to instantiate this class directly - use the methods provided by
MotorGridFSBucket
. If it is instantiated directly, callopen()
,read()
, orreadline()
before accessing its attributes.
mongomotor.metaprogramming module¶
- class mongomotor.metaprogramming.Async(cls_meth=False)[source]¶
Bases:
MotorAttributeFactory
A descriptor that wraps a mongoengine method, such as save or delete and returns an asynchronous version of the method. Usually is complementary to
OriginalDelegate
.
- class mongomotor.metaprogramming.AsyncDocumentMetaclass(name, bases, attrs)[source]¶
Bases:
AsyncWrapperMetaclass
,DocumentMetaclass
Metaclass for documents that use MotorAttributeFactory.
- class mongomotor.metaprogramming.AsyncGenericMetaclass(name, bases, attrs)[source]¶
Bases:
AsyncWrapperMetaclass
Metaclass for any type of documents that use MotorAttributeFactory.
- class mongomotor.metaprogramming.AsyncTopLevelDocumentMetaclass(name, bases, attrs)[source]¶
Bases:
AsyncWrapperMetaclass
,TopLevelDocumentMetaclass
Metaclass for top level documents that have asynchronous methods.
- class mongomotor.metaprogramming.AsyncWrapperMetaclass(name, bases, attrs)[source]¶
Bases:
type
Metaclass for classes that use MotorAttributeFactory descriptors.
- class mongomotor.metaprogramming.OriginalDelegate(doc=None)[source]¶
Bases:
MotorAttributeFactory
A descriptor that wraps a Motor method, such as insert or remove and returns the original PyMongo method. It still uses motor pool and event classes so it needs to run in a child greenlet.
This is done because I want to be able to asynchronize a method that connects to database but I want to do that in the mongoengine methods, the driver methods should work in a sync style, in order to not break the mongoengine code, but in a child greenlet to handle the I/O stuff. Usually is complementary to
Async
.
- class mongomotor.metaprogramming.Sync(cls_meth=False)[source]¶
Bases:
Async
A descriptor that wraps a mongoengine method, ensure_indexes and runs it using the synchronous pymongo driver.
- mongomotor.metaprogramming.asynchronize(method, cls_meth=False)[source]¶
Decorates method so it returns a Future.
- Parameters:
method – A mongoengine method to be asynchronized.
cls_meth – Indicates if the method being asynchronized is a class method.
mongomotor.monkey module¶
- class mongomotor.monkey.MonkeyPatcher[source]¶
Bases:
object
- patch_async_connections()[source]¶
Patches mongoengine.connection._connections removing all asynchronous connections from there.
It is used when switching to a synchronous connection to avoid mongoengine returning a asynchronous connection with the same configuration.
- patch_db_clients(client)[source]¶
Patches the db clients used to connect to mongodb.
- Parameters:
client – Which client should be used.
- patch_get_mongodb_version()[source]¶
Patches mongoengine’s get_mongodb_version to use a function does not reach the database.
- patch_item(obj, attr, newitem, undo=True)[source]¶
Sets
attr
inobj
withnewitem
. If notundo
the item will continue patched after leaving the context manager
mongomotor.queryset module¶
- class mongomotor.queryset.QuerySet(document, collection)[source]¶
Bases:
QuerySet
- async average(field)[source]¶
Average over the values of the specified field.
- Parameters:
field – the field to average over; use dot-notation to refer to embedded document fields
This method is more performant than the regular average, because it uses the aggregation framework instead of map-reduce.
- coroutine count(with_limit_and_skip=True)[source]¶
Counts the documents in the queryset.
- Parameters:
with_limit_and_skip – Indicates if limit and skip applied to the queryset should be taken into account.
- async delete(write_concern=None, _from_doc_delete=False, cascade_refs=None)[source]¶
Deletes the documents matched by the query.
- Parameters:
write_concern – Extra keyword arguments are passed down which will be used as options for the resultant
getLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server._from_doc_delete – True when called from document delete therefore signals will have been triggered so don’t loop.
:returns number of deleted documents
- coroutine distinct(field)¶
Return a list of distinct values for a given field.
- Parameters:
field – the field to select distinct values from
Note
This is a command and won’t take ordering or limit into account.
- coroutine explain()¶
Return an explain plan record for the
QuerySet
cursor.
- property fetch_next¶
- coroutine get(*q_objs, **query)[source]¶
Retrieve the the matching object raising
MultipleObjectsReturned
or DocumentName.MultipleObjectsReturned exception if multiple results andDoesNotExist
or DocumentName.DoesNotExist if no results are found.
- coroutine in_bulk(object_ids)¶
Retrieve a set of documents by their ids.
- Parameters:
object_ids – a list or tuple of ObjectId’s
- Return type:
dict of ObjectId’s as keys and collection-specific Document subclasses as values.
- coroutine insert(doc_or_docs, load_bulk=True, write_concern=None)[source]¶
bulk insert documents
- Parameters:
doc_or_docs – a document or list of documents to be inserted
(optional) (load_bulk) – If True returns the list of document instances
write_concern – Extra keyword arguments are passed down to
insert()
which will be used as options for the resultantgetLastError
command. For example,insert(..., {w: 2, fsync: True})
will wait until at least two servers have recorded the write and will force an fsync on each server being written to.
By default returns document instances, set
load_bulk
to False to return justObjectIds
- async item_frequencies(field, normalize=False)[source]¶
Returns a dictionary of all items present in a field across the whole queried set of documents, and their corresponding frequency. This is useful for generating tag clouds, or searching documents.
Note
Can only do direct simple mappings and cannot map across
ReferenceField
orGenericReferenceField
for more complex counting a manual aggretation call would be required.If the field is a
ListField
, the items within each list will be counted individually.- Parameters:
field – the field to use
normalize – normalize the results so they add to 1.0
- coroutine map_reduce(map_f, reduce_f, output, finalize_f=None, limit=None, scope=None)¶
Perform a map/reduce query using the current query spec and ordering. While
map_reduce
respectsQuerySet
chaining, it must be the last call made, as it does not return a maleableQuerySet
.See the
test_map_reduce()
andtest_map_advanced()
tests intests.queryset.QuerySetTest
for usage examples.- Parameters:
map_f – map function, as
Code
or stringreduce_f – reduce function, as
Code
or stringoutput – output collection name, if set to ‘inline’ will return the results inline. This can also be a dictionary containing output options see: http://docs.mongodb.org/manual/reference/command/mapReduce/#dbcmd.mapReduce
finalize_f – finalize function, an optional function that performs any post-reduction processing.
scope – values to insert into map/reduce global scope. Optional.
limit – number of objects from current query to provide to map/reduce method
Returns an iterator yielding
MapReduceDocument
.
- coroutine modify(upsert=False, full_response=False, remove=False, new=False, **update)¶
Update and return the updated document.
Returns either the document before or after modification based on new parameter. If no documents match the query and upsert is false, returns
None
. If upserting and new is false, returnsNone
.If the full_response parameter is
True
, the return value will be the entire response object from the server, including the ‘ok’ and ‘lastErrorObject’ fields, rather than just the modified document. This is useful mainly because the ‘lastErrorObject’ document holds information about the command’s execution.- Parameters:
upsert – insert if document doesn’t exist (default
False
)full_response – return the entire response object from the server (default
False
, not available for PyMongo 3+)remove – remove rather than updating (default
False
)new – return updated rather than original document (default
False
)update – Django-style update keyword arguments
- async sum(field)[source]¶
Sum over the values of the specified field.
- Parameters:
field – the field to sum over; use dot-notation to refer to embedded document fields
This method is more performant than the regular sum, because it uses the aggregation framework instead of map-reduce.
- coroutine to_list(length=100)[source]¶
Returns a list of the current documents in the queryset.
- Parameters:
length – maximum number of documents to return for this call.
- coroutine update(upsert=False, multi=True, write_concern=None, read_concern=None, full_result=False, **update)¶
Perform an atomic update on the fields matched by the query.
- Parameters:
upsert – insert if document doesn’t exist (default
False
)multi – Update multiple documents.
write_concern – Extra keyword arguments are passed down which will be used as options for the resultant
getLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.read_concern – Override the read concern for the operation
full_result – Return the associated
pymongo.UpdateResult
rather than just the number updated itemsupdate – Django-style update keyword arguments
:returns the number of updated documents (unless
full_result
is True)
- coroutine upsert_one(write_concern=None, **update)[source]¶
Overwrite or add the first document matched by the query.
- Parameters:
write_concern – Extra keyword arguments are passed down which will be used as options for the resultant
getLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.update – Django-style update keyword arguments
:returns the new or overwritten document
mongomotor.utils module¶
Module contents¶
- class mongomotor.Document(*args, **kwargs)[source]¶
Bases:
NoDerefInitMixin
,Document
- The base class used for defining the structure and properties of
collections of documents stored in MongoDB. Inherit from this class, and add fields as class attributes to define a document’s structure. Individual documents may then be created by making instances of the
Document
subclass.By default, the MongoDB collection used to store documents created using a
Document
subclass will be the name of the subclass converted to lowercase. A different collection may be specified by providingcollection
to themeta
dictionary in the class definition.A
Document
subclass may be itself subclassed, to create a specialised version of the document that will be stored in the same collection. To facilitate this behaviour a _cls field is added to documents (hidden though the MongoEngine interface). To disable this behaviour and remove the dependence on the presence of _cls setallow_inheritance
toFalse
in themeta
dictionary.A
Document
may use a Capped Collection by specifyingmax_documents
andmax_size
in themeta
dictionary.max_documents
is the maximum number of documents that is allowed to be stored in the collection, andmax_size
is the maximum size of the collection in bytes.max_size
is rounded up to the next multiple of 256 by MongoDB internally and mongoengine before. Use also a multiple of 256 to avoid confusions. Ifmax_size
is not specified andmax_documents
is,max_size
defaults to 10485760 bytes (10MB).Indexes may be created by specifying
indexes
in themeta
dictionary. The value should be a list of field names or tuples of field names. Index direction may be specified by prefixing the field names with a + or - sign.Automatic index creation can be enabled by specifying
auto_create_index
in themeta
dictionary. If this is set to True then indexes will be created by MongoMotor.By default, _cls will be added to the start of every index (that doesn’t contain a list) if allow_inheritance is True. This can be disabled by either setting cls to False on the specific index or by setting index_cls to False on the meta dictionary for the document.
- By default, any extra attribute existing in stored data but not declared
in your model will raise a
mongoengine.FieldDoesNotExist
error. This can be disabled by settingstrict
toFalse
in themeta
dictionary.
- classmethod compare_indexes()[source]¶
Compares the indexes defined in MongoEngine with the ones existing in the database. Returns any missing/extra indexes.
- async delete(signal_kwargs=None, **write_concern)[source]¶
Delete the
Document
from the database. This will only take effect if the document has been previously saved.- Parm signal_kwargs:
(optional) kwargs dictionary to be passed to the signal calls.
- Parameters:
write_concern – Extra keyword arguments are passed down which will be used as options for the resultant
getLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.
- classmethod drop_collection()[source]¶
Drops the entire collection associated with this
mongomotor.Document
type from the database.
- classmethod ensure_indexes()[source]¶
Checks the document meta data and ensures all the indexes exist.
Global defaults can be set in the meta - see guide/defining-documents
By default, this will get called automatically upon first interaction with the Document collection (query, save, etc) so unless you disabled auto_create_index, you shouldn’t have to call this manually.
This also gets called upon every call to Document.save if auto_create_index_on_save is set to True
If called multiple times, MongoDB will not re-recreate indexes if they exist already
Note
You can disable automatic index creation by setting auto_create_index to False in the documents meta data
- modify(query={}, **update)[source]¶
Perform an atomic update of the document in the database and reload the document object using updated version.
Returns True if the document has been updated or False if the document in the database doesn’t match the query.
Note
All unsaved changes that have been made to the document are rejected if the method returns True.
- Parameters:
query – the update will be performed only if the document in the database matches the query
update – Django-style update keyword arguments
- classmethod register_delete_rule(document_cls, field_name, rule)[source]¶
This method registers the delete rules to apply when removing this object.
- coroutine reload(*fields, **kwargs)[source]¶
Reloads all attributes from the database.
- Parameters:
fields – (optional) args list of fields to reload
max_depth – (optional) depth of dereferencing to follow
- coroutine save(force_insert=False, validate=True, clean=True, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, save_condition=None, signal_kwargs=None, **kwargs)[source]¶
Save the
Document
to the database. If the document already exists, it will be updated, otherwise it will be created. Returns the saved object instance.- Parameters:
force_insert – only try to create a new document, don’t allow updates of existing documents.
validate – validates the document; set to
False
to skip.clean – call the document clean method, requires validate to be True.
write_concern – Extra keyword arguments are passed down to
save()
ORinsert()
which will be used as options for the resultantgetLastError
command. For example,save(..., write_concern={w: 2, fsync: True}, ...)
will wait until at least two servers have recorded the write and will force an fsync on the primary server.cascade – Sets the flag for cascading saves. You can set a default by setting “cascade” in the document __meta__
cascade_kwargs – (optional) kwargs dictionary to be passed throw to cascading saves. Implies
cascade=True
._refs – A list of processed references used in cascading saves
save_condition – only perform save if matching record in db satisfies condition(s) (e.g. version number). Raises
OperationError
if the conditions are not satisfiedsignal_kwargs – (optional) kwargs dictionary to be passed to the signal calls.
- class mongomotor.DynamicEmbeddedDocument(*args, **kwargs)[source]¶
Bases:
EmbeddedDocument
A Dynamic Embedded Document class allowing flexible, expandable and uncontrolled schemas. See
DynamicDocument
for more information about dynamic documents.- my_metaclass¶
alias of
DocumentMetaclass
- class mongomotor.EmbeddedDocument(*args, **kwargs)[source]¶
Bases:
NoDerefInitMixin
,EmbeddedDocument
- class mongomotor.MapReduceDocument(document, collection, key, value)[source]¶
Bases:
object
A document returned from a map/reduce query.
- Parameters:
collection – An instance of
Collection
key – Document/result key, often an instance of
ObjectId
. If supplied as anObjectId
found in the givencollection
, the object can be accessed via theobject
property.value – The result(s) for this key.
- property object¶
Lazy-load the object referenced by
self.key
.self.key
should be theprimary_key
.
- mongomotor.connect(db=None, async_framework='asyncio', alias='default', **kwargs)[source]¶
Connect to the database specified by the ‘db’ argument.
Connection settings may be provided here as well if the database is not running on the default port on localhost. If authentication is needed, provide username and password arguments as well.
Multiple databases are supported by using aliases. Provide a separate alias to connect to a different instance of mongod.
Parameters are the same as for
mongoengine.connection.connect()
plus one:- Parameters:
async_framework – Which asynchronous framework should be used. It can be tornado or asyncio. Defaults to asyncio.