3. API Reference¶
3.1. Connecting¶
-
mongoengine.
connect
(db, 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.
Multiple databases are supported by using aliases. Provide a separate alias to connect to a different instance of mongod.
Changed in version 0.6: - added multiple database support.
-
mongoengine.
register_connection
(alias, name, host='localhost', port=27017, is_slave=False, read_preference=False, slaves=None, username=None, password=None, **kwargs)¶ Add a connection.
Parameters: - alias – the name that will be used to refer to this connection throughout MongoEngine
- name – the name of the specific database to use
- host – the host name of the mongod instance to connect to
- port – the port that the mongod instance is running on
- is_slave – whether the connection can act as a slave ** Depreciated pymongo 2.0.1+
- read_preference – The read preference for the collection ** Added pymongo 2.1
- slaves – a list of aliases of slave connections; each of these must
be a registered connection that has
is_slave
set toTrue
- username – username to authenticate with
- password – password to authenticate with
- kwargs – allow ad-hoc parameters to be passed into the pymongo driver
3.2. 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.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. Ifmax_size
is not specified andmax_documents
is,max_size
defaults to 10000000 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 disabled by specifying attr:auto_create_index in the
meta
dictionary. If this is set to False then indexes will not be created by MongoEngine. This is useful in production systems where index creation is performed as part of a deployment system.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.
Initialise a document or embedded document
Parameters: - __auto_convert – Try and will cast python objects to Object types
- values – A dictionary of values for the document
-
cascade_save
(*args, **kwargs)¶ Recursively saves any references / generic references on an objects
-
delete
(**write_concern)¶ Delete the
Document
from the database. This will only take effect if the document has been previously saved.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
()¶ Drops the entire collection associated with this
Document
type from the database.
-
classmethod
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
-
classmethod
ensure_indexes
()¶ Checks the document meta data and ensures all the indexes exist.
Note
You can disable automatic index creation by setting auto_create_index to False in the documents meta data
-
my_metaclass
¶ alias of
TopLevelDocumentMetaclass
-
classmethod
register_delete_rule
(document_cls, field_name, rule)¶ This method registers the delete rules to apply when removing this object.
-
reload
(max_depth=1)¶ Reloads all attributes from the database.
New in version 0.1.2.
Changed in version 0.6: Now chainable
-
save
(force_insert=False, validate=True, clean=True, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, **kwargs)¶ Save the
Document
to the database. If the document already exists, it will be updated, otherwise it will be created.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
- _refs – A list of processed references used in cascading saves
Changed in version 0.5: In existing documents it only saves changed fields using set / unset. Saves are cascaded and any
DBRef
objects that have changes are saved as well.Changed in version 0.6: Cascade saves are optional = defaults to True, if you want fine grain control then you can turn off using document meta[‘cascade’] = False Also you can pass different kwargs to the cascade save using cascade_kwargs which overwrites the existing kwargs with custom values
Handles dereferencing of
DBRef
objects to a maximum depth in order to cut down the number queries to mongodb.New in version 0.5.
-
switch_collection
(collection_name)¶ Temporarily switch the collection for a document instance.
Only really useful for archiving off data and calling save():
user = User.objects.get(id=user_id) user.switch_collection('old-users') user.save()
If you need to read from another database see
switch_db
Parameters: collection_name – The database alias to use for saving the document
-
switch_db
(db_alias)¶ Temporarily switch the database for a document instance.
Only really useful for archiving off data and calling save():
user = User.objects.get(id=user_id) user.switch_db('archive-db') user.save()
If you need to read from another database see
switch_db
Parameters: db_alias – The database alias to use for saving the document
-
to_dbref
()¶ Returns an instance of
DBRef
useful in __raw__ queries.
-
class
mongoengine.
EmbeddedDocument
(*args, **kwargs)¶ A
Document
that isn’t stored in its own collection.EmbeddedDocument
s should be used as fields onDocument
s through theEmbeddedDocumentField
field type.A
EmbeddedDocument
subclass may be itself subclassed, to create a specialised version of the embedded 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.-
my_metaclass
¶ alias of
DocumentMetaclass
-
-
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 theDynamicDocument
that is not a field is automatically converted into aDynamicField
and data can be attributed to that field.Note
There is one caveat on Dynamic Documents: fields cannot start with _
Initialise a document or embedded document
Parameters: - __auto_convert – Try and will cast python objects to Object types
- values – A dictionary of values for the document
-
my_metaclass
¶ alias of
TopLevelDocumentMetaclass
-
class
mongoengine.
DynamicEmbeddedDocument
(*args, **kwargs)¶ 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
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 anObjectId
found in the givencollection
, the object can be accessed via theobject
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 theprimary_key
.
- collection – An instance of
-
class
mongoengine.
ValidationError
(message='', **kwargs)¶ Validation exception.
May represent an error validating a field or a document containing fields with validation errors.
Variables: errors – A dictionary of errors for fields within this document or list, or None if the error is for an individual field. -
to_dict
()¶ Returns a dictionary of all errors within a document
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.
-
3.3. Context Managers¶
-
class
mongoengine.context_managers.
switch_db
(cls, db_alias)¶ switch_db alias context manager.
Example
# Register connections register_connection('default', 'mongoenginetest') register_connection('testdb-1', 'mongoenginetest2') class Group(Document): name = StringField() Group(name="test").save() # Saves in the default db with switch_db(Group, 'testdb-1') as Group: Group(name="hello testdb!").save() # Saves in testdb-1
Construct the switch_db context manager
Parameters: - cls – the class to change the registered db
- db_alias – the name of the specific database to use
-
class
mongoengine.context_managers.
no_dereference
(cls)¶ no_dereference context manager.
Turns off all dereferencing in Documents for the duration of the context manager:
with no_dereference(Group) as Group: Group.objects.find()
Construct the no_dereference context manager.
Parameters: cls – the class to turn dereferencing off on
-
class
mongoengine.context_managers.
query_counter
¶ Query_counter context manager to get the number of queries.
Construct the query_counter.
3.4. 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, class_check=True, slave_okay=False, read_preference=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; theQuerySet
is filtered multiple times with differentQ
objects, only the last one will be used - class_check – If set to False bypass class name check when querying collection
- slave_okay – if True, allows this query to be run against a replica secondary.
- query – Django-style query keyword arguments
Params read_preference: if set, overrides connection-level read_preference from ReplicaSetConnection.
- q_obj – a
-
all
()¶ Returns all documents.
-
all_fields
()¶ Include all fields. Reset all previously calls of .only() or .exclude().
post = BlogPost.objects.exclude("comments").all_fields()
New in version 0.5.
-
as_pymongo
(coerce_types=False)¶ Instead of returning Document instances, return raw values from pymongo.
Parameters: coerce_type – Field types (if applicable) would be use to coerce types.
-
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 Changed in version 0.5: - updated to map_reduce as db.eval doesnt work with sharding.
-
count
(with_limit_and_skip=True)¶ Count the selected elements in the query.
Parameters: (optional) (with_limit_and_skip) – take any limit()
orskip()
that has been applied to this cursor into account when getting the count
-
create
(**kwargs)¶ Create new object. Returns the saved object instance.
New in version 0.4.
-
delete
(write_concern=None)¶ Delete 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.
-
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.
New in version 0.4.
Changed in version 0.5: - Fixed handling references
Changed in version 0.6: - Improved db_field refrence handling
-
ensure_index
(**kwargs)¶ Deprecated use
ensure_index()
-
exclude
(*fields)¶ Opposite to .only(), exclude some document’s fields.
post = BlogPost.objects(...).exclude("comments")
Note
exclude() is chainable and will perform a union :: So with the following it will exclude both: title and author.name:
post = BlogPost.objects.exclude("title").exclude("author.name")
all_fields()
will reset any field filters.Parameters: fields – fields to exclude New in version 0.5.
-
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; andoptions
, 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 aField
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
-
fields
(_only_called=False, **kwargs)¶ Manipulate how you load this document’s fields. Used by .only() and .exclude() to manipulate which fields to retrieve. Fields also allows for a greater level of control for example:
Retrieving a Subrange of Array Elements:
You can use the $slice operator to retrieve a subrange of elements in an array. For example to get the first 5 comments:
post = BlogPost.objects(...).fields(slice__comments=5)
Parameters: kwargs – A dictionary identifying what to include New in version 0.5.
-
filter
(*q_objs, **query)¶ An alias of
__call__()
-
first
()¶ Retrieve the first object matching the query.
-
from_json
(json_data)¶ Converts json data to unsaved objects
-
get
(*q_objs, **query)¶ Retrieve the the matching object raising
MultipleObjectsReturned
or DocumentName.MultipleObjectsReturned exception if multiple results andDoesNotExist
or DocumentName.DoesNotExist if no results are found.New in version 0.3.
-
get_or_create
(write_concern=None, auto_save=True, *q_objs, **query)¶ Retrieve unique object or create, if it doesn’t exist. Returns a tuple of
(object, created)
, whereobject
is the retrieved or created object andcreated
is a boolean specifying whether a new object was created. RaisesMultipleObjectsReturned
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 calleddefaults
.Note
This requires two separate operations and therefore a race condition exists. Because there are no transactions in mongoDB other approaches should be investigated, to ensure you don’t accidently duplicate data when using this method. This is now scheduled to be removed before 1.0
Parameters: - write_concern – optional extra keyword arguments used if we
have to create a new document.
Passes any write_concern onto
save()
- auto_save – if the object is to be saved automatically if not found.
Deprecated since version 0.8.
Changed in version 0.6: - added auto_save
New in version 0.3.
- write_concern – optional extra keyword arguments used if we
have to create a new document.
Passes any write_concern onto
-
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. When doing a query on multiple fields (at least one of which is indexed) pass the indexed field as a hint to the query.
Hinting will not do anything if the corresponding index does not exist. The last hint applied to this cursor takes precedence over all others.
New in version 0.5.
-
in_bulk
(object_ids)¶ Retrieve a set of documents by their ids.
Parameters: object_ids – a list or tuple of ObjectId
sReturn type: dict of ObjectIds as keys and collection-specific Document subclasses as values. New in version 0.3.
-
insert
(doc_or_docs, load_bulk=True, write_concern=None)¶ bulk insert documents
Parameters: - docs_or_doc – 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
New in version 0.5.
-
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 searching documents.
Note
Can only do direct simple mappings and cannot map across
ReferenceField
orGenericReferenceField
for more complex counting a manual map reduce call would is 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
- map_reduce – Use map_reduce over exec_js
Changed in version 0.5: defaults to map_reduce and can handle embedded document lookups
-
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, 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 string - reduce_f – reduce function, as
Code
or string - output – output collection name, if set to ‘inline’ will try to
use
inline_map_reduce
This can also be a dictionary containing output options see: http://docs.mongodb.org/manual/reference/commands/#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
.Note
Map/Reduce changed in server version >= 1.7.4. The PyMongo
map_reduce()
helper requires PyMongo version >= 1.11.Changed in version 0.5: - removed
keep_temp
keyword argument, which was only relevant for MongoDB server versions older than 1.7.4New in version 0.3.
- map_f – map function, as
-
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 just returns a list
-
only
(*fields)¶ Load only a subset of this document’s fields.
post = BlogPost.objects(...).only("title", "author.name")
Note
only() is chainable and will perform a union :: So with the following it will fetch both: title and author.name:
post = BlogPost.objects.only("title").only("author.name")
all_fields()
will reset any field filters.Parameters: fields – fields to include New in version 0.3.
Changed in version 0.5: - Added subfield support
-
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
-
read_preference
(read_preference)¶ Change the read_preference when querying.
Parameters: read_preference – override ReplicaSetConnection-level preference.
-
rewind
()¶ Rewind the cursor to its unevaluated state.
New in version 0.3.
-
scalar
(*fields)¶ Instead of returning Document instances, return either a specific value or a tuple of values in order.
Can be used along with
no_dereference()
to turn off dereferencing.Note
This effects all results and can be unset by calling
scalar
without arguments. Callsonly
automatically.Parameters: fields – One or more fields to return instead of a Document.
Handles dereferencing of
DBRef
objects orObjectId
a maximum depth in order to cut down the number queries to mongodb.New in version 0.5.
-
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
-
slave_okay
(enabled)¶ Enable or disable the slave_okay when querying.
Parameters: enabled – whether or not the slave_okay is enabled
-
snapshot
(enabled)¶ Enable or disable snapshot mode when querying.
Parameters: enabled – whether or not snapshot mode is enabled ..versionchanged:: 0.5 - made chainable
-
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 Changed in version 0.5: - updated to map_reduce as db.eval doesnt work with sharding.
-
timeout
(enabled)¶ Enable or disable the default mongod timeout when querying.
Parameters: enabled – whether or not the timeout is used ..versionchanged:: 0.5 - made chainable
-
to_json
()¶ Converts a queryset to JSON
-
update
(upsert=False, multi=True, write_concern=None, **update)¶ Perform an atomic update on the fields matched by the query.
Parameters: - upsert – Any existing document with that “_id” is overwritten.
- 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. - update – Django-style update keyword arguments
New in version 0.2.
-
update_one
(upsert=False, write_concern=None, **update)¶ Perform an atomic update on first field matched by the query.
Parameters: - upsert – Any existing document with that “_id” is overwritten.
- 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
New in version 0.2.
-
values_list
(*fields)¶ An alias for scalar
-
where
(where_clause)¶ Filter
QuerySet
results with a$where
clause (a Javascript expression). Performs automatic field name substitution likemongoengine.queryset.Queryset.exec_js()
.Note
When using this mode of query, the database will call your function, or evaluate your predicate clause, for each object in the collection.
New in version 0.5.
-
with_id
(object_id)¶ Retrieve the object matching the id provided. Uses object_id only and raises InvalidQueryError if a filter has been applied. Returns None if no document exists with that id.
Parameters: object_id – the value for the id of the document to look up Changed in version 0.6: Raises InvalidQueryError if filter has been set
-
-
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 aDocument
class as its first argument, and aQuerySet
as its second argument. The method function should return aQuerySet
, probably the same one that was passed in, but modified in some way.
3.5. Fields¶
-
class
mongoengine.fields.
StringField
(regex=None, max_length=None, min_length=None, **kwargs)¶ A unicode string field.
-
class
mongoengine.fields.
URLField
(verify_exists=False, url_regex=None, **kwargs)¶ A field that validates input as an URL.
New in version 0.3.
-
class
mongoengine.fields.
EmailField
(regex=None, max_length=None, min_length=None, **kwargs)¶ A field that validates input as an E-Mail-Address.
New in version 0.4.
-
class
mongoengine.fields.
IntField
(min_value=None, max_value=None, **kwargs)¶ An 32-bit integer field.
-
class
mongoengine.fields.
LongField
(min_value=None, max_value=None, **kwargs)¶ An 64-bit integer field.
-
class
mongoengine.fields.
FloatField
(min_value=None, max_value=None, **kwargs)¶ An 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.
Changed in version 0.8.
New in version 0.3.
Parameters: - min_value – Validation rule for the minimum acceptable value.
- max_value – Validation rule for the maximum acceptable value.
- force_string – Store as a string.
- precision – Number of decimal places to store.
- rounding –
The rounding rule from the python decimal libary:
- decimial.ROUND_CEILING (towards Infinity)
- decimial.ROUND_DOWN (towards zero)
- decimial.ROUND_FLOOR (towards -Infinity)
- decimial.ROUND_HALF_DOWN (to nearest with ties going towards zero)
- decimial.ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)
- decimial.ROUND_HALF_UP (to nearest with ties going away from zero)
- decimial.ROUND_UP (away from zero)
- decimial.ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
Defaults to:
decimal.ROUND_HALF_UP
-
class
mongoengine.fields.
BooleanField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A boolean field type.
New in version 0.1.2.
-
class
mongoengine.fields.
DateTimeField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A datetime field.
- Note: Microseconds are rounded to the nearest millisecond.
- Pre UTC microsecond support is effecively broken.
Use
ComplexDateTimeField
if you need accurate microsecond support.
-
class
mongoengine.fields.
ComplexDateTimeField
(separator=', ', **kwargs)¶ ComplexDateTimeField 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.
The stored string has the following format:
YYYY,MM,DD,HH,MM,SS,NNNNNNWhere NNNNNN is the number of microseconds of the represented datetime. The , as the separator can be easily modified by passing the separator keyword when initializing the field.
New in version 0.5.
-
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
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A generic embedded document field - allows any
EmbeddedDocument
to be stored.Only valid values are subclasses of
EmbeddedDocument
.Note
You can use the choices param to limit the acceptable EmbeddedDocument types
-
class
mongoengine.fields.
DynamicField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A truly dynamic field type capable of handling different and varying types of data.
Used by
DynamicDocument
to handle dynamic data
-
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.
If using with ReferenceFields see: One to Many with ListFields
Note
Required means it cannot be empty - as the default for ListFields is []
-
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.
Warning
There is a potential race condition when handling lists. If you set / save the whole list then other processes trying to save the whole list as well could overwrite changes. The safest way to append to a list is to perform a push operation.
New in version 0.4.
Changed in version 0.6: - added reverse keyword
-
class
mongoengine.fields.
DictField
(basecls=None, 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.
Note
Required means it cannot be empty - as the default for ListFields is []
New in version 0.3.
Changed in version 0.5: - Can now handle complex / varying types of data
-
class
mongoengine.fields.
MapField
(field=None, *args, **kwargs)¶ A field that maps a name to a specified field type. Similar to a DictField, except the ‘value’ of each item must match the specified field type.
New in version 0.5.
-
class
mongoengine.fields.
ReferenceField
(document_type, dbref=False, reverse_delete_rule=0, **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. EmbeddedDocuments, DictFields and MapFields do not support reverse_delete_rules and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.
The options are:
DO_NOTHING - don’t do anything (default).
NULLIFY - Updates the reference to null.
CASCADE - Deletes the documents associated with the reference.
DENY - Prevent the deletion of the reference object.
- PULL - Pull the reference from a
ListField
of references
- PULL - Pull the reference from a
Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)
class Bar(Document): content = StringField() foo = ReferenceField('Foo') Bar.register_delete_rule(Foo, 'bar', NULLIFY)
Note
reverse_delete_rules do not trigger pre / post delete signals to be triggered.
Changed in version 0.5: added reverse_delete_rule
Initialises the Reference Field.
Parameters: - dbref – Store the reference as
DBRef
or as theObjectId
.id . - reverse_delete_rule – Determines what to do when the referring object is deleted
-
class
mongoengine.fields.
GenericReferenceField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A reference to any
Document
subclass that will be automatically dereferenced on access (lazily).Note
- Any documents used as a generic reference must be registered in the document registry. Importing the model will automatically register it.
- You can use the choices param to limit the acceptable Document types
New in version 0.3.
-
class
mongoengine.fields.
BinaryField
(max_bytes=None, **kwargs)¶ A binary data field.
-
class
mongoengine.fields.
FileField
(db_alias='default', collection_name='fs', **kwargs)¶ A GridFS storage field.
New in version 0.4.
Changed in version 0.5: added optional size param for read
Changed in version 0.6: added db_alias for multidb support
-
class
mongoengine.fields.
ImageField
(size=None, thumbnail_size=None, collection_name='images', **kwargs)¶ A Image File storage field.
- @size (width, height, force):
- max size to store images, if larger will be automatically resized ex: size=(800, 600, True)
- @thumbnail (width, height, force):
- size to generate a thumbnail
New in version 0.6.
-
class
mongoengine.fields.
SequenceField
(collection_name=None, db_alias=None, sequence_name=None, value_decorator=None, *args, **kwargs)¶ - Provides a sequental counter see:
- http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-SequenceNumbers
Note
Although traditional databases often use increasing sequence numbers for primary keys. In MongoDB, the preferred approach is to use Object IDs instead. The concept is that in a very large cluster of machines, it is easier to create an object ID than have global, uniformly increasing sequence numbers.
Use any callable as value_decorator to transform calculated counter into any value suitable for your needs, e.g. string or hexadecimal representation of the default integer counter value.
New in version 0.5.
Changed in version 0.8: added value_decorator
-
class
mongoengine.fields.
ObjectIdField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A field wrapper around MongoDB’s ObjectIds.
-
class
mongoengine.fields.
UUIDField
(binary=True, **kwargs)¶ A UUID field.
New in version 0.6.
Store UUID data in the database
Parameters: binary – if False store as a string. Changed in version 0.8.0.
Changed in version 0.6.19.
-
class
mongoengine.fields.
GeoPointField
(db_field=None, name=None, required=False, default=None, unique=False, unique_with=None, primary_key=False, validation=None, choices=None, verbose_name=None, help_text=None)¶ A list storing a latitude and longitude.
New in version 0.4.
-
class
mongoengine.fields.
PointField
(auto_index=True, *args, **kwargs)¶ A geo json field storing a latitude and longitude.
The data is represented as:
{ "type" : "Point" , "coordinates" : [x, y]}
You can either pass a dict with the full information or a list to set the value.
Requires mongodb >= 2.4 .. versionadded:: 0.8
Parameters: auto_index – Automatically create a “2dsphere” index. Defaults to True.
-
class
mongoengine.fields.
LineStringField
(auto_index=True, *args, **kwargs)¶ A geo json field storing a line of latitude and longitude coordinates.
The data is represented as:
{ "type" : "LineString" , "coordinates" : [[x1, y1], [x1, y1] ... [xn, yn]]}
You can either pass a dict with the full information or a list of points.
Requires mongodb >= 2.4 .. versionadded:: 0.8
Parameters: auto_index – Automatically create a “2dsphere” index. Defaults to True.
-
class
mongoengine.fields.
PolygonField
(auto_index=True, *args, **kwargs)¶ A geo json field storing a polygon of latitude and longitude coordinates.
The data is represented as:
{ "type" : "Polygon" , "coordinates" : [[[x1, y1], [x1, y1] ... [xn, yn]], [[x1, y1], [x1, y1] ... [xn, yn]]}
You can either pass a dict with the full information or a list of LineStrings. The first LineString being the outside and the rest being holes.
Requires mongodb >= 2.4 .. versionadded:: 0.8
Parameters: auto_index – Automatically create a “2dsphere” index. Defaults to True.
-
class
mongoengine.fields.
GridFSError
¶
-
class
mongoengine.fields.
GridFSProxy
(grid_id=None, key=None, instance=None, db_alias='default', collection_name='fs')¶ Proxy object to handle writing and reading of files to and from GridFS
New in version 0.4.
Changed in version 0.5: - added optional size param to read
Changed in version 0.6: - added collection name param
-
class
mongoengine.fields.
ImageGridFsProxy
(grid_id=None, key=None, instance=None, db_alias='default', collection_name='fs')¶ Proxy for ImageField
versionadded: 0.6
-
class
mongoengine.fields.
ImproperlyConfigured
¶