API Reference

Connecting

mongoengine.connect(db, username=None, password=None, **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.

Documents

class mongoengine.Document(**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.

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 providing collection to the meta 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, _cls and _types fields are added to documents (hidden though the MongoEngine interface though). To disable this behaviour and remove the dependence on the presence of _cls and _types, set allow_inheritance to False in the meta dictionary.

A Document may use a Capped Collection by specifying max_documents and max_size in the meta dictionary. max_documents is the maximum number of documents that is allowed to be stored in the collection, and max_size is the maximum size of the collection in bytes. If max_size is not specified and max_documents is, max_size defaults to 10000000 bytes (10MB).

Indexes may be created by specifying indexes in the meta 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.

objects

A QuerySet object that is created lazily on access.

delete(safe=False)

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

Parameters:safe – check if the operation succeeded before returning
classmethod drop_collection()

Drops the entire collection associated with this Document type from the database.

reload()

Reloads all attributes from the database.

New in version 0.1.2.

save(safe=True, force_insert=False, validate=True)

Save the Document to the database. If the document already exists, it will be updated, otherwise it will be created.

If safe=True and the operation is unsuccessful, an OperationError will be raised.

Parameters:
  • safe – check if the operation succeeded before returning
  • force_insert – only try to create a new document, don’t allow updates of existing documents
  • validate – validates the document; set to False for skiping
class mongoengine.EmbeddedDocument(**values)

A Document that isn’t stored in its own collection. EmbeddedDocuments should be used as fields on Documents through the EmbeddedDocumentField field type.

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

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 an ObjectId found in the given collection, the object can be accessed via the object property.
  • value – The result(s) for this key.

New in version 0.3.

object

Lazy-load the object referenced by self.key. self.key should be the primary_key.

Querying

class mongoengine.queryset.QuerySet(document, collection)

A set of results returned from a query. Wraps a MongoDB cursor, providing Document objects as the results.

__call__(q_obj=None, **query)

Filter the selected documents by calling the QuerySet with a query.

Parameters:
  • q_obj – a Q object to be used in the query; the QuerySet is filtered multiple times with different Q objects, only the last one will be used
  • query – Django-style query keyword arguments
all()

Returns all documents.

average(field)

Average over the values of the specified field.

Parameters:field – the field to average over; use dot-notation to refer to embedded document fields
count()

Count the selected elements in the query.

create(**kwargs)

Create new object. Returns the saved object instance.

New in version 0.4.

delete(safe=False)

Delete the documents matched by the query.

Parameters:safe – check if the operation succeeded before returning
distinct(field)

Return a list of distinct values for a given field.

Parameters:field – the field to select distinct values from

New in version 0.4.

ensure_index(key_or_list, drop_dups=False, background=False, **kwargs)

Ensure that the given indexes are in place.

Parameters:key_or_list – a single index key or a list of index keys (to construct a multi-field index); keys may be prefixed with a + or a - to determine the index ordering
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. A few extra variables are added to the function’s scope: collection, which is the name of the collection in use; query, which is an object representing the current query; and options, which is an object containing any options specified as keyword arguments.

As fields in MongoEngine may use different names in the database (set using the db_field keyword argument to a Field constructor), a mechanism exists for replacing MongoEngine field names with the database field names in Javascript code. When accessing a field, use square-bracket notation, and prefix the MongoEngine field name with a tilde (~).

Parameters:
  • code – a string of Javascript code to execute
  • fields – fields that you will be using in your function, which will be passed in to your function as arguments
  • options – options that you want available to the function (accessed in Javascript through the options object)
explain(format=False)

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

Parameters:format – format the plan before returning it
filter(*q_objs, **query)

An alias of __call__()

first()

Retrieve the first object matching the query.

get(*q_objs, **query)

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

New in version 0.3.

get_or_create(*q_objs, **query)

Retrieve unique object or create, if it doesn’t exist. Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created. Raises MultipleObjectsReturned or DocumentName.MultipleObjectsReturned if multiple results are found. A new document will be created if the document doesn’t exists; a dictionary of default values for the new document may be provided as a keyword argument called defaults.

New in version 0.3.

in_bulk(object_ids)

Retrieve a set of documents by their ids.

Parameters:object_ids – a list or tuple of ObjectIds
Return type:dict of ObjectIds as keys and collection-specific Document subclasses as values.

New in version 0.3.

item_frequencies(field, normalize=False)

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.

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
limit(n)

Limit the number of returned documents to n. This may also be achieved using array-slicing syntax (e.g. User.objects[:5]).

Parameters:n – the maximum number of objects to return
map_reduce(map_f, reduce_f, finalize_f=None, limit=None, scope=None, keep_temp=False)

Perform a map/reduce query using the current query spec and ordering. While map_reduce respects QuerySet chaining, it must be the last call made, as it does not return a maleable QuerySet.

See the test_map_reduce() and test_map_advanced() tests in tests.queryset.QuerySetTest for usage examples.

Parameters:
  • map_f – map function, as Code or string
  • reduce_f – reduce function, as Code or string
  • 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
  • keep_temp – keep temporary table (boolean, default True)

Returns an iterator yielding MapReduceDocument.

Note

Map/Reduce requires server version >= 1.1.1. The PyMongo map_reduce() helper requires PyMongo version >= 1.2.

New in version 0.3.

next()

Wrap the result in a Document object.

only(*fields)

Load only a subset of this document’s fields.

post = BlogPost.objects(...).only("title")
Parameters:fields – fields to include

New in version 0.3.

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 order is assumed.

Parameters:keys – fields to order the query results by; keys may be prefixed with + or - to determine the ordering direction
rewind()

Rewind the cursor to its unevaluated state.

New in version 0.3.

skip(n)

Skip n documents before returning the results. This may also be achieved using array-slicing syntax (e.g. User.objects[5:]).

Parameters:n – the number of objects to skip before returning results
snapshot(enabled)

Enable or disable snapshot mode when querying.

Parameters:enabled – whether or not snapshot mode is enabled
sum(field)

Sum over the values of the specified field.

Parameters:field – the field to sum over; use dot-notation to refer to embedded document fields
timeout(enabled)

Enable or disable the default mongod timeout when querying.

Parameters:enabled – whether or not the timeout is used
update(safe_update=True, upsert=False, **update)

Perform an atomic update on the fields matched by the query. When safe_update is used, the number of affected documents is returned.

Parameters:
  • safe – check if the operation succeeded before returning
  • update – Django-style update keyword arguments

New in version 0.2.

update_one(safe_update=True, upsert=False, **update)

Perform an atomic update on first field matched by the query. When safe_update is used, the number of affected documents is returned.

Parameters:
  • safe – check if the operation succeeded before returning
  • update – Django-style update keyword arguments

New in version 0.2.

with_id(object_id)

Retrieve the object matching the id provided.

Parameters:object_id – the value for the id of the document to look up
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.

Fields

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

A unicode string field.

class mongoengine.URLField(verify_exists=False, **kwargs)

A field that validates input as an URL.

New in version 0.3.

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

An integer field.

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

An floating point number field.

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

A fixed-point decimal number field.

New in version 0.3.

class mongoengine.BooleanField(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None)

A boolean field type.

New in version 0.1.2.

class mongoengine.DateTimeField(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None)

A datetime field.

class mongoengine.EmbeddedDocumentField(document_type, **kwargs)

An embedded document field. Only valid values are subclasses of EmbeddedDocument.

class mongoengine.DictField(basecls=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.

New in version 0.3.

class mongoengine.ListField(field, **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.BinaryField(max_bytes=None, **kwargs)

A binary data field.

class mongoengine.ObjectIdField(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None)

An field wrapper around MongoDB’s ObjectIds.

class mongoengine.ReferenceField(document_type, **kwargs)

A reference to a document that will be automatically dereferenced on access (lazily).

class mongoengine.GenericReferenceField(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None)

A reference to any Document subclass that will be automatically dereferenced on access (lazily).

New in version 0.3.

class mongoengine.FileField(**kwargs)

A GridFS storage field.

New in version 0.4.

class mongoengine.GeoPointField(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None)

A list storing a latitude and longitude.

New in version 0.4.

Table Of Contents

Previous topic

GridFS

Next topic

Using MongoEngine with Django

This Page