3. API Reference
Connecting
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
mongodinstance to connect to - port
- the port that the
mongodinstance is running on - username
- username to authenticate with
- password
- password to authenticate with
- authentication_source
- database to authenticate against
- authentication_mechanism
- database authentication mechanisms
Close the connection with a given alias. In case the alias has not been registered, a MongoEngineConnectionError will be raised.
Close all registered database connections.
Return the PyMongo connection with a given alias. In case the alias has not been registered, a MongoEngineConnectionError will be raised.
Return the database with a given alias. Raises MongoEngineConnectionError if the alias is not registered.
Register the connection settings.
Documents
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.
A QuerySet object that is created lazily on access.
Compares the indexes defined in MongoEngine with the ones existing in the database. Returns any missing/extra indexes.
Creates the given indexes if required.
Delete the Document from the database. This will only take effect if the document has been previously saved.
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).
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.
Lists all of the indexes that should be created for the given collection. It includes all the indexes from super- and sub-classes.
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.
Get the primary key.
This method registers the delete rules to apply when removing this object.
Reloads all attributes from the database.
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
Falseto skip - clean
- call the document clean method, requires
validateto beTrue - write_concern
- extra keyword arguments are passed down to
save()ORinsert() - 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
Handles dereferencing of DBRef objects to a maximum depth in order to cut down the number of queries to MongoDB.
Returns an instance of DBRef useful in __raw__ queries.
Convert this document to JSON.
Return as SON data ready for use with MongoDB.
Performs an update on the Document. A convenience wrapper to update(). Raises OperationError if called on an object that has not yet been saved.
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.
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.
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.
A Dynamic Embedded Document class allowing flexible, expandable and uncontrolled schemas. See DynamicDocument for more information about dynamic documents.
A document returned from a map/reduce query.
Retrieves the object from the document's key.
Validation exception. May represent an error validating a field or a document containing fields with validation 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.
Returns a dictionary of all errors within a document.
Querying
The default queryset, that builds queries and handles a database cursor.
Perform a MongoDB aggregation pipeline on this queryset. The pipeline is passed directly to PyMongo.
Returns a copy of the current QuerySet.
Average over the values of the specified field.
Limit the number of documents returned in a single batch (each batch requires a round trip).
Creates a copy of the current QuerySet.
Add a comment to the query.
Count the selected elements in the query.
Create new object. Returns the saved object instance.
Delete the documents matched by the query.
Return a list of distinct values for a given field.
Opposite to .only(), exclude some document's fields. exclude() is chainable and will perform a union.
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.
Return an explain plan record for the QuerySet's cursor.
Manipulate how you load this document's fields. Used by .only() and .exclude() to manipulate which fields to retrieve.
An alias of QuerySet.__call__.
Retrieve the first object matching the query.
Retrieve the matching object raising MultipleObjectsReturned or DocumentName.MultipleObjectsReturned exception if multiple results, and DoesNotExist or DocumentName.DoesNotExist if no results are found.
Added 'hint' support, telling Mongo the proper index to use for the query. Judicious use of hints can greatly improve query performance.
Retrieve a set of documents by their ids.
Bulk insert a list of documents. By default returns document instances, set load_bulk to False to return just ObjectIds.
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 the number of returned documents to n. This may also be achieved using Python's slice notation, e.g. User.objects[:5].
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.
Convert to a non-caching queryset.
Turn off any dereferencing for the results of this queryset.
Only return instances of this document and not any inherited documents.
Helper that returns a queryset that never returns any objects and no query will be executed when accessing the results.
Load only a subset of this document's fields. only() is chainable and will perform a union.
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.
Change the read_concern when querying.
Change the read_preference when querying.
Start a text search, using text indexes. Requires MongoDB server version 2.6+.
Handles dereferencing of DBRef objects to a maximum depth in order to cut down the number of queries to MongoDB.
Skip n documents before returning the results. This may also be achieved using Python's slice notation e.g. User.objects[5:].
Sum over the values of the specified field.
Enable or disable the default mongod timeout when querying. Useful if you are doing a long running query.
Convert this queryset to JSON.
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
getLastErrorcommand - full_result
- Return the associated
pymongo.UpdateResultrather than just the number
Perform an atomic update on the fields of the first document matched by the query.
This method is for controlling which database the QuerySet will be evaluated against if you are using more than one database.
An iterator which returns lists instead of document instances.
Filter QuerySet results with a $where clause (a Javascript expression). Performs automatic field name substitution like exec_js().
A non-caching QuerySet.
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.
Additional queries for Embedded Documents are available when using the EmbeddedDocumentListField to store a list of embedded documents.
The number of embedded documents in the list.
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.
Deletes the embedded documents from the database. The embedded document changes are not automatically saved to the database after calling this method.
Filters the list by excluding embedded documents with the given keyword arguments.
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.
Return the first embedded document in the list, or None if empty.
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.
Saves the ancestor document.
Updates the embedded documents with the given keyword arguments. The embedded document changes are not automatically saved to the database after calling this method.
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:
db_field— The MongoDB field name.required— IfTrue, the field must have a value. Defaults toFalse.default— A default value (or callable).unique— WhenTrue, no documents in the collection will have the same value for this field.unique_with— The other field(s) this field should be unique with.primary_key— WhenTrue, use this field as the primary key.choices— An iterable of choices to which the value of this field should be limited.validation— A callable to validate the value of the field.null— IfTrue, the field value can be null when a default exists.
A unicode string field.
A field that validates input as a URL.
A field that validates input as an email address.
A 32-bit integer field.
A 64-bit integer field. Deprecated — use IntField instead.
A floating point number field.
A fixed-point decimal number field.
A boolean field type.
A datetime field. Uses Python's datetime object to store the date and time.
A date field. Uses Python's date object to store the date.
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.
A field wrapper around MongoDB's ObjectIds.
A UUID field.
A binary data field.
A list field that wraps a standard field, allowing multiple instances of the field to be used as a list in the database.
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.
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.
A dictionary field that wraps a standard Python dictionary. This is similar to an embedded document, but the structure is not defined.
A field that maps a name to a specified field type. Similar to DictField, except the 'value' field can be specified.
An embedded document field — with a declared document_type. Only valid values are subclasses of EmbeddedDocument.
A generic embedded document field — allows any EmbeddedDocument to be stored. Only valid values are subclasses of EmbeddedDocument.
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:
DO_NOTHING(0) — don't do anything (default)NULLIFY(1) — updates the reference to nullCASCADE(2) — deletes the documents associated with the referenceDENY(3) — prevent the deletion of the reference objectPULL(4) — pull the reference from aListFieldof references
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.
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.
A reference to a document. Unlike ReferenceField, the reference is not automatically dereferenced on access. You must call fetch() to get the referenced document.
A reference to any Document subclass. Unlike GenericReferenceField, the reference is not automatically dereferenced on access.
A GridFS storage field. See GridFS for more information.
A GridFS storage field for images. Inherits from FileField.
Provides a sequential counter (using a sequence collection in MongoDB). Works like an auto-increment field in traditional ORMs.
Provides storage for Python's Enum type. The value is stored as the enum value in MongoDB.
A list storing a latitude and longitude. Aliased as PointField as the 2dsphere index is preferred.
A GeoJSON field storing a Point. The data is stored as a GeoJSON Point object.
A GeoJSON field storing a LineString.
A GeoJSON field storing a Polygon.
A GeoJSON field storing a list of Points.
A GeoJSON field storing a list of LineStrings.
A GeoJSON field storing a list of Polygons.
Signals
See the Signals guide for more details.
Called during the creation of a new Document or EmbeddedDocument instance, before default values are assigned.
Called after all processing of a new Document or EmbeddedDocument instance has been completed.
Called within save() prior to performing any actions.
Called within save() after validation has taken place but before saving.
Called within save() after all actions have completed successfully.
Called within delete() prior to attempting the delete operation.
Called within delete() upon successful deletion of the record.
Called after validation of the documents to insert, but prior to any data being written.
Called after a successful bulk insert operation.
Context Managers
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'
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.
Turn off any dereferencing for the given class.
Only return instances of this document and not any inherited documents.
A context manager to count the number of queries issued to MongoDB. Useful for performance testing.
Errors
Validation exception raised when a document fails validation.
Raised when trying to set a field not declared in a Document or an EmbeddedDocument.
Raised when a document is incorrectly defined.
Raised when attempting to lookup an unknown field.
Raised when a Document.get() query returns no results.
Raised when a Document.get() query returns more than one result.
Raised when an invalid query is made.
Raised when a database operation fails.
Raised when a uniqueness constraint is violated.
Raised when a save_condition fails on a Document.save().
Raised when a connection to MongoDB fails or when attempting to use an alias that has not been registered.