3. API Reference

Connecting

mongoengine.connect(db=None, alias='default', **kwargs)

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.

db
the name of the database to use, for compatibility with connect
alias
the name that will be used to refer to this connection throughout MongoEngine
host
the host name of the mongod instance to connect to
port
the port that the mongod instance is running on
username
username to authenticate with
password
password to authenticate with
authentication_source
database to authenticate against
authentication_mechanism
database authentication mechanisms
mongoengine.disconnect(alias='default')

Close the connection with a given alias. In case the alias has not been registered, a MongoEngineConnectionError will be raised.

mongoengine.disconnect_all()

Close all registered database connections.

mongoengine.get_connection(alias='default', reconnect=False)

Return the PyMongo connection with a given alias. In case the alias has not been registered, a MongoEngineConnectionError will be raised.

mongoengine.get_db(alias='default', reconnect=False)

Return the database with a given alias. Raises MongoEngineConnectionError if the alias is not registered.

mongoengine.register_connection(alias, db=None, **kwargs)

Register the connection settings.

Documents

class mongoengine.Document(*args, **values)

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.

attribute objects

A QuerySet object that is created lazily on access.

classmethod compare_indexes()

Compares the indexes defined in MongoEngine with the ones existing in the database. Returns any missing/extra indexes.

classmethod create_index(keys, background=False, **kwargs)

Creates the given indexes if required.

delete(signal_kwargs=None, **write_concern)

Delete the Document from the database. This will only take effect if the document has been previously saved.

classmethod drop_collection()

Drops the entire collection associated with this Document type from the database. Raises OperationError if the document has no collection set (e.g. if it is abstract).

classmethod ensure_indexes()

Checks the document meta data and ensures all the indexes exist. Global defaults can be set in the meta. You can disable automatic index creation by setting auto_create_index to False in the document's meta data.

classmethod list_indexes()

Lists all of the indexes that should be created for the given collection. It includes all the indexes from super- and sub-classes.

modify(query=None, **update)

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.

pk

Get the primary key.

classmethod register_delete_rule(document_cls, field_name, rule)

This method registers the delete rules to apply when removing this object.

reload(*fields, **kwargs)

Reloads all attributes from the database.

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)

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.

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() OR insert()
cascade
sets the flag for cascading saves
save_condition
only perform save if matching record in db satisfies condition(s)
signal_kwargs
kwargs dictionary to be passed to the signal calls
select_related(max_depth=1)

Handles dereferencing of DBRef objects to a maximum depth in order to cut down the number of queries to MongoDB.

to_dbref()

Returns an instance of DBRef useful in __raw__ queries.

to_json(**kwargs)

Convert this document to JSON.

to_mongo(use_db_field=True, fields=None)

Return as SON data ready for use with MongoDB.

update(**kwargs)

Performs an update on the Document. A convenience wrapper to update(). Raises OperationError if called on an object that has not yet been saved.

validate(clean=True)

Ensure that all fields' values are valid and that required fields are present. Raises ValidationError if any of the fields' values are found to be invalid.

class mongoengine.EmbeddedDocument(*args, **kwargs)

A Document that isn't stored in its own collection. EmbeddedDocuments should be used as fields on Documents through the EmbeddedDocumentField field type. An EmbeddedDocument subclass may itself be subclassed, to create a specialised version of the embedded document that will be stored in the same collection.

class mongoengine.DynamicDocument(*args, **values)

A Dynamic Document class allowing flexible, expandable and uncontrolled schemas. As a Document subclass, acts in the same way as an ordinary document but has expando style properties. Any data passed or set against the DynamicDocument that is not a field is automatically converted into a DynamicField and data can be attributed to that field.

class mongoengine.DynamicEmbeddedDocument(*args, **kwargs)

A Dynamic Embedded Document class allowing flexible, expandable and uncontrolled schemas. See DynamicDocument for more information about dynamic documents.

class mongoengine.document.MapReduceDocument(document, collection, key, value)

A document returned from a map/reduce query.

object

Retrieves the object from the document's key.

class mongoengine.ValidationError(message='', **kwargs)

Validation exception. May represent an error validating a field or a document containing fields with validation errors.

errors

A dictionary of errors. Keys are field names or list indices and values are the validation error messages, or a nested dictionary of errors for an embedded document or list.

to_dict()

Returns a dictionary of all errors within a document.

Querying

class mongoengine.queryset.QuerySet(document, collection)

The default queryset, that builds queries and handles a database cursor.

aggregate(*pipeline, **kwargs)

Perform a MongoDB aggregation pipeline on this queryset. The pipeline is passed directly to PyMongo.

all()

Returns a copy of the current QuerySet.

average(field)

Average over the values of the specified field.

batch_size(size)

Limit the number of documents returned in a single batch (each batch requires a round trip).

clone()

Creates a copy of the current QuerySet.

comment(text)

Add a comment to the query.

count(with_limit_and_skip=False)

Count the selected elements in the query.

create(**kwargs)

Create new object. Returns the saved object instance.

delete(write_concern=None, _from_doc_delete=False, cascade_refs=None)

Delete the documents matched by the query.

distinct(field)

Return a list of distinct values for a given field.

exclude(*fields)

Opposite to .only(), exclude some document's fields. exclude() is chainable and will perform a union.

exec_js(code, *fields, **options)

Execute a Javascript function on the server. A list of fields may be provided, which will be translated to their correct names and supplied as the arguments to the function.

explain()

Return an explain plan record for the QuerySet's cursor.

fields(to_use=None, **kwargs)

Manipulate how you load this document's fields. Used by .only() and .exclude() to manipulate which fields to retrieve.

filter(*q_objs, **query)

An alias of QuerySet.__call__.

first()

Retrieve the first object matching the query.

get(*q_objs, **query)

Retrieve the matching object raising MultipleObjectsReturned or DocumentName.MultipleObjectsReturned exception if multiple results, and DoesNotExist or DocumentName.DoesNotExist if no results are found.

hint(index=None)

Added 'hint' support, telling Mongo the proper index to use for the query. Judicious use of hints can greatly improve query performance.

in_bulk(object_ids)

Retrieve a set of documents by their ids.

insert(doc_or_docs, load_bulk=True, write_concern=None, signal_kwargs=None)

Bulk insert a list of documents. By default returns document instances, set load_bulk to False to return just ObjectIds.

item_frequencies(field, normalize=False, map_reduce=True)

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 other such graphs.

limit(n)

Limit the number of returned documents to n. This may also be achieved using Python's slice notation, e.g. User.objects[:5].

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 no documents match the query, create and return (as new) the new document.

no_cache()

Convert to a non-caching queryset.

no_dereference()

Turn off any dereferencing for the results of this queryset.

no_sub_classes()

Only return instances of this document and not any inherited documents.

none()

Helper that returns a queryset that never returns any objects and no query will be executed when accessing the results.

only(*fields)

Load only a subset of this document's fields. only() is chainable and will perform a union.

order_by(*keys)

Order the QuerySet by the keys. The order may be specified by prepending each of the keys by a + or a -. Ascending is the default.

read_concern(read_concern)

Change the read_concern when querying.

read_preference(read_preference)

Change the read_preference when querying.

search_text(text, language=None)

Start a text search, using text indexes. Requires MongoDB server version 2.6+.

select_related(max_depth=1)

Handles dereferencing of DBRef objects to a maximum depth in order to cut down the number of queries to MongoDB.

skip(n)

Skip n documents before returning the results. This may also be achieved using Python's slice notation e.g. User.objects[5:].

sum(field)

Sum over the values of the specified field.

timeout(enabled)

Enable or disable the default mongod timeout when querying. Useful if you are doing a long running query.

to_json(**kwargs)

Convert this queryset to JSON.

update(upsert=False, multi=True, write_concern=None, full_result=False, **update)

Perform an atomic update on the fields matched by the query.

upsert
Any existing document with that criteria is updated, any existing documents are left intact
multi
Update multiple documents
write_concern
Extra keyword arguments are passed down which will be used as options for the resultant getLastError command
full_result
Return the associated pymongo.UpdateResult rather than just the number
update_one(upsert=False, write_concern=None, full_result=False, **update)

Perform an atomic update on the fields of the first document matched by the query.

using(alias)

This method is for controlling which database the QuerySet will be evaluated against if you are using more than one database.

values_list(*fields)

An iterator which returns lists instead of document instances.

where(where_clause)

Filter QuerySet results with a $where clause (a Javascript expression). Performs automatic field name substitution like exec_js().

class mongoengine.queryset.QuerySetNoCache(document, collection)

A non-caching QuerySet.

mongoengine.queryset.queryset_manager(func)

Decorator that allows you to define custom QuerySet managers on Document classes. The manager must be a function that accepts a Document class as its first argument, and a QuerySet as its second argument. The method function should return a QuerySet, probably the same one that was passed in, but modified in some way.

class mongoengine.base.datastructures.EmbeddedDocumentList(list_items, instance, name)

Additional queries for Embedded Documents are available when using the EmbeddedDocumentListField to store a list of embedded documents.

count()

The number of embedded documents in the list.

create(**values)

Creates a new embedded document and saves it to the database. The embedded document changes are not automatically saved to the database after calling this method.

delete()

Deletes the embedded documents from the database. The embedded document changes are not automatically saved to the database after calling this method.

exclude(**kwargs)

Filters the list by excluding embedded documents with the given keyword arguments.

filter(**kwargs)

Filters the list by only including embedded documents with the given keyword arguments. Raises AttributeError if a given keyword is not a valid field for the embedded document class.

first()

Return the first embedded document in the list, or None if empty.

get(**kwargs)

Retrieves an embedded document determined by the given keyword arguments. Raises DoesNotExist if no document is found and MultipleObjectsReturned if more than one document is found.

save()

Saves the ancestor document.

update(**update)

Updates the embedded documents with the given keyword arguments. The embedded document changes are not automatically saved to the database after calling this method.

class mongoengine.queryset.Q(*q_objs, **query)

A simple query object, used in a query tree to build up more complex query structures using & (and) and | (or) operators.

Fields

All field types accept the following base keyword arguments:

class mongoengine.fields.StringField(regex=None, max_length=None, min_length=None, **kwargs)

A unicode string field.

class mongoengine.fields.URLField(url_regex=None, schemes=None, **kwargs)

A field that validates input as a URL.

class mongoengine.fields.EmailField(regex=None, max_length=None, min_length=None, **kwargs)

A field that validates input as an email address.

class mongoengine.fields.IntField(min_value=None, max_value=None, **kwargs)

A 32-bit integer field.

class mongoengine.fields.LongField(min_value=None, max_value=None, **kwargs)

A 64-bit integer field. Deprecated — use IntField instead.

class mongoengine.fields.FloatField(min_value=None, max_value=None, **kwargs)

A floating point number field.

class mongoengine.fields.DecimalField(min_value=None, max_value=None, force_string=False, precision=2, rounding='ROUND_HALF_UP', **kwargs)

A fixed-point decimal number field.

class mongoengine.fields.BooleanField(**kwargs)

A boolean field type.

class mongoengine.fields.DateTimeField(**kwargs)

A datetime field. Uses Python's datetime object to store the date and time.

class mongoengine.fields.DateField(**kwargs)

A date field. Uses Python's date object to store the date.

class mongoengine.fields.ComplexDateTimeField(separator=', ', **kwargs)

Handles microseconds exactly instead of rounding like DateTimeField does. Derives from a StringField so you can do gte and lte filtering by using lexicographical comparison when filtering/sorting strings.

class mongoengine.fields.ObjectIdField(**kwargs)

A field wrapper around MongoDB's ObjectIds.

class mongoengine.fields.UUIDField(binary=True, **kwargs)

A UUID field.

class mongoengine.fields.BinaryField(max_bytes=None, **kwargs)

A binary data field.

class mongoengine.fields.ListField(field=None, **kwargs)

A list field that wraps a standard field, allowing multiple instances of the field to be used as a list in the database.

class mongoengine.fields.SortedListField(field, **kwargs)

A ListField that sorts the contents of its list before writing to the database in order to ensure that a sorted list is always retrieved.

class mongoengine.fields.EmbeddedDocumentListField(document_type, **kwargs)

A ListField designed specially to hold a list of embedded documents to provide additional query helpers. The only valid list values are subclasses of EmbeddedDocument.

class mongoengine.fields.DictField(field=None, *args, **kwargs)

A dictionary field that wraps a standard Python dictionary. This is similar to an embedded document, but the structure is not defined.

class mongoengine.fields.MapField(field=None, *args, **kwargs)

A field that maps a name to a specified field type. Similar to DictField, except the 'value' field can be specified.

class mongoengine.fields.EmbeddedDocumentField(document_type, **kwargs)

An embedded document field — with a declared document_type. Only valid values are subclasses of EmbeddedDocument.

class mongoengine.fields.GenericEmbeddedDocumentField(**kwargs)

A generic embedded document field — allows any EmbeddedDocument to be stored. Only valid values are subclasses of EmbeddedDocument.

class mongoengine.fields.ReferenceField(document_type, dbref=False, reverse_delete_rule=DO_NOTHING, **kwargs)

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.

The accepted values for reverse_delete_rule are:

class mongoengine.fields.GenericReferenceField(*args, **kwargs)

A reference to any Document subclass that will be automatically dereferenced on access (lazily). Any documents used as a generic reference must be registered in the document registry. Importing the model will automatically register it.

class mongoengine.fields.CachedReferenceField(document_type, fields=[], auto_sync=True, **kwargs)

A reference field with cache. Stores the selected fields of the referenced document in the document itself. Useful to avoid having to dereference the document when all that's needed is a few fields.

class mongoengine.fields.LazyReferenceField(document_type, passthrough=False, dbref=False, reverse_delete_rule=DO_NOTHING, **kwargs)

A reference to a document. Unlike ReferenceField, the reference is not automatically dereferenced on access. You must call fetch() to get the referenced document.

class mongoengine.fields.GenericLazyReferenceField(*args, **kwargs)

A reference to any Document subclass. Unlike GenericReferenceField, the reference is not automatically dereferenced on access.

class mongoengine.fields.FileField(db_alias='default', collection_name='fs', **kwargs)

A GridFS storage field. See GridFS for more information.

class mongoengine.fields.ImageField(size=None, thumbnail_size=None, collection_name='images', **kwargs)

A GridFS storage field for images. Inherits from FileField.

class mongoengine.fields.SequenceField(collection_name=None, db_alias='default', sequence_name=None, value_decorator=None, *args, **kwargs)

Provides a sequential counter (using a sequence collection in MongoDB). Works like an auto-increment field in traditional ORMs.

class mongoengine.fields.EnumField(enum, **kwargs)

Provides storage for Python's Enum type. The value is stored as the enum value in MongoDB.

class mongoengine.fields.GeoPointField(**kwargs)

A list storing a latitude and longitude. Aliased as PointField as the 2dsphere index is preferred.

class mongoengine.fields.PointField(auto_index=True, **kwargs)

A GeoJSON field storing a Point. The data is stored as a GeoJSON Point object.

class mongoengine.fields.LineStringField(auto_index=True, **kwargs)

A GeoJSON field storing a LineString.

class mongoengine.fields.PolygonField(auto_index=True, **kwargs)

A GeoJSON field storing a Polygon.

class mongoengine.fields.MultiPointField(auto_index=True, **kwargs)

A GeoJSON field storing a list of Points.

class mongoengine.fields.MultiLineStringField(auto_index=True, **kwargs)

A GeoJSON field storing a list of LineStrings.

class mongoengine.fields.MultiPolygonField(auto_index=True, **kwargs)

A GeoJSON field storing a list of Polygons.

Signals

See the Signals guide for more details.

mongoengine.signals.pre_init

Called during the creation of a new Document or EmbeddedDocument instance, before default values are assigned.

mongoengine.signals.post_init

Called after all processing of a new Document or EmbeddedDocument instance has been completed.

mongoengine.signals.pre_save

Called within save() prior to performing any actions.

mongoengine.signals.pre_save_post_validation

Called within save() after validation has taken place but before saving.

mongoengine.signals.post_save

Called within save() after all actions have completed successfully.

mongoengine.signals.pre_delete

Called within delete() prior to attempting the delete operation.

mongoengine.signals.post_delete

Called within delete() upon successful deletion of the record.

mongoengine.signals.pre_bulk_insert

Called after validation of the documents to insert, but prior to any data being written.

mongoengine.signals.post_bulk_insert

Called after a successful bulk insert operation.

Context Managers

class mongoengine.context_managers.switch_db(cls, db_alias)

The switch_db context manager allows you to change the database alias for a given class, allowing quick and easy access to the same Document across databases.

with switch_db(User, 'archive-user-db') as User:
    User(name='Ross').save()  # Saves to 'archive-user-db'
class mongoengine.context_managers.switch_collection(cls, collection_name)

The switch_collection context manager allows you to change the collection for a given class, allowing quick and easy access to the same Document across collections.

class mongoengine.context_managers.no_dereference(cls)

Turn off any dereferencing for the given class.

class mongoengine.context_managers.no_sub_classes(cls)

Only return instances of this document and not any inherited documents.

class mongoengine.context_managers.query_counter(alias='default')

A context manager to count the number of queries issued to MongoDB. Useful for performance testing.

Errors

exception mongoengine.ValidationError(message='', **kwargs)

Validation exception raised when a document fails validation.

exception mongoengine.errors.FieldDoesNotExist

Raised when trying to set a field not declared in a Document or an EmbeddedDocument.

exception mongoengine.errors.InvalidDocumentError

Raised when a document is incorrectly defined.

exception mongoengine.errors.LookUpError

Raised when attempting to lookup an unknown field.

exception mongoengine.errors.DoesNotExist

Raised when a Document.get() query returns no results.

exception mongoengine.errors.MultipleObjectsReturned

Raised when a Document.get() query returns more than one result.

exception mongoengine.errors.InvalidQueryError

Raised when an invalid query is made.

exception mongoengine.errors.OperationError

Raised when a database operation fails.

exception mongoengine.errors.NotUniqueError

Raised when a uniqueness constraint is violated.

exception mongoengine.errors.SaveConditionError

Raised when a save_condition fails on a Document.save().

exception mongoengine.errors.MongoEngineConnectionError

Raised when a connection to MongoDB fails or when attempting to use an alias that has not been registered.