<!-- # hard line break macro for HTML -->

# fiftyone.core.odm.document

Base classes for documents that back dataset contents.

Copyright 2017-2026, Voxel51, Inc.
<br/>
[voxel51.com](https://voxel51.com/)
<br/>
<br/>

**Classes:**

| [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)()         | Mixin for documents that can be serialized in BSON or JSON format.                                                                                                             |
|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`MongoEngineBaseDocument`](#fiftyone.core.odm.document.MongoEngineBaseDocument)()   | Mixin for all `mongoengine:mongoengine.base.BaseDocument` subclasses that implements the [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) interface. |
| [`DynamicMixin`](#fiftyone.core.odm.document.DynamicMixin)()                         | Mixin for [`MongoEngineBaseDocument`](#fiftyone.core.odm.document.MongoEngineBaseDocument) classes that can have arbitrary dynamic fields added to them.                       |
| [`BaseDocument`](#fiftyone.core.odm.document.BaseDocument)()                         | Base class for documents that are written to the database in their own collections.                                                                                            |
| [`DynamicDocument`](#fiftyone.core.odm.document.DynamicDocument)(\*args, \*\*values) | Base class for dynamic documents that are stored in a MongoDB collection.                                                                                                      |
| [`Document`](#fiftyone.core.odm.document.Document)(\*\*kwargs)                       | Base class for documents that are stored in a MongoDB collection.                                                                                                              |

### *class* fiftyone.core.odm.document.SerializableDocument

Bases: `object`

Mixin for documents that can be serialized in BSON or JSON format.

**Attributes:**

| [`field_names`](#fiftyone.core.odm.document.SerializableDocument.field_names)   | An ordered tuple of the public fields of this document.   |
|---------------------------------------------------------------------------------|-----------------------------------------------------------|

**Methods:**

| [`fancy_repr`](#fiftyone.core.odm.document.SerializableDocument.fancy_repr)([class_name, select_fields, ...])   | Generates a customizable string representation of the document.                          |
|-----------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`has_field`](#fiftyone.core.odm.document.SerializableDocument.has_field)(field_name)                           | Determines whether the document has a field of the given name.                           |
| [`get_field`](#fiftyone.core.odm.document.SerializableDocument.get_field)(field_name)                           | Gets the field of the document.                                                          |
| [`set_field`](#fiftyone.core.odm.document.SerializableDocument.set_field)(field_name, value[, create])          | Sets the value of a field of the document.                                               |
| [`clear_field`](#fiftyone.core.odm.document.SerializableDocument.clear_field)(field_name)                       | Clears the field from the document.                                                      |
| [`iter_fields`](#fiftyone.core.odm.document.SerializableDocument.iter_fields)()                                 | Returns an iterator over the `(name, value)` pairs of the public fields of the document. |
| [`copy`](#fiftyone.core.odm.document.SerializableDocument.copy)()                                               | Returns a deep copy of the document.                                                     |
| [`merge`](#fiftyone.core.odm.document.SerializableDocument.merge)(doc[, merge_lists, merge_dicts, overwrite])   | Merges the contents of the given document into this document.                            |
| [`to_dict`](#fiftyone.core.odm.document.SerializableDocument.to_dict)([extended])                               | Serializes this document to a BSON/JSON dictionary.                                      |
| [`from_dict`](#fiftyone.core.odm.document.SerializableDocument.from_dict)(d[, extended])                        | Loads the document from a BSON/JSON dictionary.                                          |
| [`to_json`](#fiftyone.core.odm.document.SerializableDocument.to_json)([pretty_print])                           | Serializes the document to a JSON string.                                                |
| [`from_json`](#fiftyone.core.odm.document.SerializableDocument.from_json)(s)                                    | Loads the document from a JSON string.                                                   |

#### *property* field_names

An ordered tuple of the public fields of this document.

#### fancy_repr(class_name=None, select_fields=None, exclude_fields=None, \*\*kwargs)

Generates a customizable string representation of the document.

* **Parameters:**
  * **class_name** (*None*) – optional class name to use
  * **select_fields** (*None*) – iterable of field names to restrict to
  * **exclude_fields** (*None*) – iterable of field names to exclude
  * **\*\*kwargs** – additional key-value pairs to include in the string
    representation
* **Returns:**
  a string representation of the document

#### has_field(field_name)

Determines whether the document has a field of the given name.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  True/False

#### get_field(field_name)

Gets the field of the document.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  the field value
* **Raises:**
  **AttributeError** – if the field does not exist

#### set_field(field_name, value, create=True)

Sets the value of a field of the document.

* **Parameters:**
  * **field_name** – the field name
  * **value** – the field value
  * **create** (*True*) – whether to create the field if it does not exist
* **Raises:**
  **ValueError** – if `field_name` is not an allowed field name or does
      not exist and `create == False`

#### clear_field(field_name)

Clears the field from the document.

* **Parameters:**
  **field_name** – the field name
* **Raises:**
  **ValueError** – if the field does not exist

#### iter_fields()

Returns an iterator over the `(name, value)` pairs of the
public fields of the document.

* **Returns:**
  an iterator that emits `(name, value)` tuples

#### copy()

Returns a deep copy of the document.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### merge(doc, merge_lists=True, merge_dicts=True, overwrite=True)

Merges the contents of the given document into this document.

* **Parameters:**
  * **doc** – a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) of same type as this document
  * **merge_lists** (*True*) – whether to merge the elements of top-level list
    fields rather than treating the list as a single value
  * **merge_dicts** (*True*) – whether to recursively merge the contents of
    top-level dict fields rather than treating the dict as a single
    value
  * **overwrite** (*True*) – whether to overwrite (True) or skip (False)
    existing fields

#### to_dict(extended=False)

Serializes this document to a BSON/JSON dictionary.

* **Parameters:**
  **extended** (*False*) – whether to serialize extended JSON constructs
  such as ObjectIDs, Binary, etc. into JSON format
* **Returns:**
  a dict

#### *classmethod* from_dict(d, extended=False)

Loads the document from a BSON/JSON dictionary.

* **Parameters:**
  * **d** – a dictionary
  * **extended** (*False*) – whether the input dictionary may contain
    serialized extended JSON constructs
* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### to_json(pretty_print=False)

Serializes the document to a JSON string.

* **Parameters:**
  **pretty_print** (*False*) – whether to render the JSON in human readable
  format with newlines and indentations
* **Returns:**
  a JSON string

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

### *class* fiftyone.core.odm.document.MongoEngineBaseDocument

Bases: [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

Mixin for all `mongoengine:mongoengine.base.BaseDocument`
subclasses that implements the [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) interface.

**Attributes:**

| [`field_names`](#fiftyone.core.odm.document.MongoEngineBaseDocument.field_names)   | An ordered tuple of the public fields of this document.   |
|------------------------------------------------------------------------------------|-----------------------------------------------------------|

**Methods:**

| [`has_field`](#fiftyone.core.odm.document.MongoEngineBaseDocument.has_field)(field_name)                         | Determines whether the document has a field of the given name.                           |
|------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`get_field`](#fiftyone.core.odm.document.MongoEngineBaseDocument.get_field)(field_name)                         | Gets the field of the document.                                                          |
| [`set_field`](#fiftyone.core.odm.document.MongoEngineBaseDocument.set_field)(field_name, value[, create])        | Sets the value of a field of the document.                                               |
| [`clear_field`](#fiftyone.core.odm.document.MongoEngineBaseDocument.clear_field)(field_name)                     | Clears the field from the document.                                                      |
| [`field_to_mongo`](#fiftyone.core.odm.document.MongoEngineBaseDocument.field_to_mongo)(field_name)               |                                                                                          |
| [`field_to_python`](#fiftyone.core.odm.document.MongoEngineBaseDocument.field_to_python)(field_name, value)      |                                                                                          |
| [`to_dict`](#fiftyone.core.odm.document.MongoEngineBaseDocument.to_dict)([extended])                             | Serializes this document to a BSON/JSON dictionary.                                      |
| [`from_dict`](#fiftyone.core.odm.document.MongoEngineBaseDocument.from_dict)(d[, extended])                      | Loads the document from a BSON/JSON dictionary.                                          |
| [`copy`](#fiftyone.core.odm.document.MongoEngineBaseDocument.copy)()                                             | Returns a deep copy of the document.                                                     |
| [`fancy_repr`](#fiftyone.core.odm.document.MongoEngineBaseDocument.fancy_repr)([class_name, select_fields, ...]) | Generates a customizable string representation of the document.                          |
| [`from_json`](#fiftyone.core.odm.document.MongoEngineBaseDocument.from_json)(s)                                  | Loads the document from a JSON string.                                                   |
| [`iter_fields`](#fiftyone.core.odm.document.MongoEngineBaseDocument.iter_fields)()                               | Returns an iterator over the `(name, value)` pairs of the public fields of the document. |
| [`merge`](#fiftyone.core.odm.document.MongoEngineBaseDocument.merge)(doc[, merge_lists, merge_dicts, overwrite]) | Merges the contents of the given document into this document.                            |
| [`to_json`](#fiftyone.core.odm.document.MongoEngineBaseDocument.to_json)([pretty_print])                         | Serializes the document to a JSON string.                                                |

#### *property* field_names

An ordered tuple of the public fields of this document.

#### has_field(field_name)

Determines whether the document has a field of the given name.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  True/False

#### get_field(field_name)

Gets the field of the document.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  the field value
* **Raises:**
  **AttributeError** – if the field does not exist

#### set_field(field_name, value, create=True)

Sets the value of a field of the document.

* **Parameters:**
  * **field_name** – the field name
  * **value** – the field value
  * **create** (*True*) – whether to create the field if it does not exist
* **Raises:**
  **ValueError** – if `field_name` is not an allowed field name or does
      not exist and `create == False`

#### clear_field(field_name)

Clears the field from the document.

* **Parameters:**
  **field_name** – the field name
* **Raises:**
  **ValueError** – if the field does not exist

#### field_to_mongo(field_name)

#### field_to_python(field_name, value)

#### to_dict(extended=False)

Serializes this document to a BSON/JSON dictionary.

* **Parameters:**
  **extended** (*False*) – whether to serialize extended JSON constructs
  such as ObjectIDs, Binary, etc. into JSON format
* **Returns:**
  a dict

#### *classmethod* from_dict(d, extended=False)

Loads the document from a BSON/JSON dictionary.

* **Parameters:**
  * **d** – a dictionary
  * **extended** (*False*) – whether the input dictionary may contain
    serialized extended JSON constructs
* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### copy()

Returns a deep copy of the document.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### fancy_repr(class_name=None, select_fields=None, exclude_fields=None, \*\*kwargs)

Generates a customizable string representation of the document.

* **Parameters:**
  * **class_name** (*None*) – optional class name to use
  * **select_fields** (*None*) – iterable of field names to restrict to
  * **exclude_fields** (*None*) – iterable of field names to exclude
  * **\*\*kwargs** – additional key-value pairs to include in the string
    representation
* **Returns:**
  a string representation of the document

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### iter_fields()

Returns an iterator over the `(name, value)` pairs of the
public fields of the document.

* **Returns:**
  an iterator that emits `(name, value)` tuples

#### merge(doc, merge_lists=True, merge_dicts=True, overwrite=True)

Merges the contents of the given document into this document.

* **Parameters:**
  * **doc** – a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) of same type as this document
  * **merge_lists** (*True*) – whether to merge the elements of top-level list
    fields rather than treating the list as a single value
  * **merge_dicts** (*True*) – whether to recursively merge the contents of
    top-level dict fields rather than treating the dict as a single
    value
  * **overwrite** (*True*) – whether to overwrite (True) or skip (False)
    existing fields

#### to_json(pretty_print=False)

Serializes the document to a JSON string.

* **Parameters:**
  **pretty_print** (*False*) – whether to render the JSON in human readable
  format with newlines and indentations
* **Returns:**
  a JSON string

### *class* fiftyone.core.odm.document.DynamicMixin

Bases: `object`

Mixin for [`MongoEngineBaseDocument`](#fiftyone.core.odm.document.MongoEngineBaseDocument) classes that can have
arbitrary dynamic fields added to them.

**Methods:**

| [`to_mongo`](#fiftyone.core.odm.document.DynamicMixin.to_mongo)(\*args, \*\*kwargs)   |    |
|---------------------------------------------------------------------------------------|----|

#### to_mongo(\*args, \*\*kwargs)

### *class* fiftyone.core.odm.document.BaseDocument

Bases: [`MongoEngineBaseDocument`](#fiftyone.core.odm.document.MongoEngineBaseDocument)

Base class for documents that are written to the database in their own
collections.

The ID of a document is automatically populated when it is added to the
database, and the ID of a document is `None` if it has not been added to
the database.

#### id

the ID of the document, or `None` if it has not been added to the
database

**Attributes:**

| [`in_db`](#fiftyone.core.odm.document.BaseDocument.in_db)             | Whether the document has been inserted into the database.   |
|-----------------------------------------------------------------------|-------------------------------------------------------------|
| [`field_names`](#fiftyone.core.odm.document.BaseDocument.field_names) | An ordered tuple of the public fields of this document.     |

**Methods:**

| [`clear_field`](#fiftyone.core.odm.document.BaseDocument.clear_field)(field_name)                     | Clears the field from the document.                                                      |
|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`copy`](#fiftyone.core.odm.document.BaseDocument.copy)()                                             | Returns a deep copy of the document.                                                     |
| [`fancy_repr`](#fiftyone.core.odm.document.BaseDocument.fancy_repr)([class_name, select_fields, ...]) | Generates a customizable string representation of the document.                          |
| [`field_to_mongo`](#fiftyone.core.odm.document.BaseDocument.field_to_mongo)(field_name)               |                                                                                          |
| [`field_to_python`](#fiftyone.core.odm.document.BaseDocument.field_to_python)(field_name, value)      |                                                                                          |
| [`from_dict`](#fiftyone.core.odm.document.BaseDocument.from_dict)(d[, extended])                      | Loads the document from a BSON/JSON dictionary.                                          |
| [`from_json`](#fiftyone.core.odm.document.BaseDocument.from_json)(s)                                  | Loads the document from a JSON string.                                                   |
| [`get_field`](#fiftyone.core.odm.document.BaseDocument.get_field)(field_name)                         | Gets the field of the document.                                                          |
| [`has_field`](#fiftyone.core.odm.document.BaseDocument.has_field)(field_name)                         | Determines whether the document has a field of the given name.                           |
| [`iter_fields`](#fiftyone.core.odm.document.BaseDocument.iter_fields)()                               | Returns an iterator over the `(name, value)` pairs of the public fields of the document. |
| [`merge`](#fiftyone.core.odm.document.BaseDocument.merge)(doc[, merge_lists, merge_dicts, overwrite]) | Merges the contents of the given document into this document.                            |
| [`set_field`](#fiftyone.core.odm.document.BaseDocument.set_field)(field_name, value[, create])        | Sets the value of a field of the document.                                               |
| [`to_dict`](#fiftyone.core.odm.document.BaseDocument.to_dict)([extended])                             | Serializes this document to a BSON/JSON dictionary.                                      |
| [`to_json`](#fiftyone.core.odm.document.BaseDocument.to_json)([pretty_print])                         | Serializes the document to a JSON string.                                                |

#### *property* in_db

Whether the document has been inserted into the database.

#### clear_field(field_name)

Clears the field from the document.

* **Parameters:**
  **field_name** – the field name
* **Raises:**
  **ValueError** – if the field does not exist

#### copy()

Returns a deep copy of the document.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### fancy_repr(class_name=None, select_fields=None, exclude_fields=None, \*\*kwargs)

Generates a customizable string representation of the document.

* **Parameters:**
  * **class_name** (*None*) – optional class name to use
  * **select_fields** (*None*) – iterable of field names to restrict to
  * **exclude_fields** (*None*) – iterable of field names to exclude
  * **\*\*kwargs** – additional key-value pairs to include in the string
    representation
* **Returns:**
  a string representation of the document

#### *property* field_names

An ordered tuple of the public fields of this document.

#### field_to_mongo(field_name)

#### field_to_python(field_name, value)

#### *classmethod* from_dict(d, extended=False)

Loads the document from a BSON/JSON dictionary.

* **Parameters:**
  * **d** – a dictionary
  * **extended** (*False*) – whether the input dictionary may contain
    serialized extended JSON constructs
* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### get_field(field_name)

Gets the field of the document.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  the field value
* **Raises:**
  **AttributeError** – if the field does not exist

#### has_field(field_name)

Determines whether the document has a field of the given name.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  True/False

#### iter_fields()

Returns an iterator over the `(name, value)` pairs of the
public fields of the document.

* **Returns:**
  an iterator that emits `(name, value)` tuples

#### merge(doc, merge_lists=True, merge_dicts=True, overwrite=True)

Merges the contents of the given document into this document.

* **Parameters:**
  * **doc** – a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) of same type as this document
  * **merge_lists** (*True*) – whether to merge the elements of top-level list
    fields rather than treating the list as a single value
  * **merge_dicts** (*True*) – whether to recursively merge the contents of
    top-level dict fields rather than treating the dict as a single
    value
  * **overwrite** (*True*) – whether to overwrite (True) or skip (False)
    existing fields

#### set_field(field_name, value, create=True)

Sets the value of a field of the document.

* **Parameters:**
  * **field_name** – the field name
  * **value** – the field value
  * **create** (*True*) – whether to create the field if it does not exist
* **Raises:**
  **ValueError** – if `field_name` is not an allowed field name or does
      not exist and `create == False`

#### to_dict(extended=False)

Serializes this document to a BSON/JSON dictionary.

* **Parameters:**
  **extended** (*False*) – whether to serialize extended JSON constructs
  such as ObjectIDs, Binary, etc. into JSON format
* **Returns:**
  a dict

#### to_json(pretty_print=False)

Serializes the document to a JSON string.

* **Parameters:**
  **pretty_print** (*False*) – whether to render the JSON in human readable
  format with newlines and indentations
* **Returns:**
  a JSON string

### *class* fiftyone.core.odm.document.DynamicDocument(\*args, \*\*values)

Bases: [`DynamicMixin`](#fiftyone.core.odm.document.DynamicMixin), [`BaseDocument`](#fiftyone.core.odm.document.BaseDocument), `DynamicDocument`

Base class for dynamic documents that are stored in a MongoDB
collection.

Dynamic documents can have arbitrary fields added to them.

The ID of a document is automatically populated when it is added to the
database, and the ID of a document is `None` if it has not been added to
the database.

#### id

the ID of the document, or `None` if it has not been added to the
database

**Attributes:**

| [`STRICT`](#fiftyone.core.odm.document.DynamicDocument.STRICT)           |                                                           |
|--------------------------------------------------------------------------|-----------------------------------------------------------|
| [`field_names`](#fiftyone.core.odm.document.DynamicDocument.field_names) | An ordered tuple of the public fields of this document.   |
| [`in_db`](#fiftyone.core.odm.document.DynamicDocument.in_db)             | Whether the document has been inserted into the database. |
| [`pk`](#fiftyone.core.odm.document.DynamicDocument.pk)                   | Get the primary key.                                      |

**Methods:**

| [`cascade_save`](#fiftyone.core.odm.document.DynamicDocument.cascade_save)(\*\*kwargs)                        | Recursively save any references and generic references on the document.                                                                                                                          |
|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`clean`](#fiftyone.core.odm.document.DynamicDocument.clean)()                                                | Hook for doing document level data cleaning (usually validation or assignment) before validation is run.                                                                                         |
| [`clear_field`](#fiftyone.core.odm.document.DynamicDocument.clear_field)(field_name)                          | Clears the field from the document.                                                                                                                                                              |
| [`compare_indexes`](#fiftyone.core.odm.document.DynamicDocument.compare_indexes)()                            | Compares the indexes defined in MongoEngine with the ones existing in the database.                                                                                                              |
| [`copy`](#fiftyone.core.odm.document.DynamicDocument.copy)()                                                  | Returns a deep copy of the document.                                                                                                                                                             |
| [`create_index`](#fiftyone.core.odm.document.DynamicDocument.create_index)(keys[, background])                | Creates the given indexes if required.                                                                                                                                                           |
| [`delete`](#fiftyone.core.odm.document.DynamicDocument.delete)([signal_kwargs])                               | Delete the `Document` from the database.                                                                                                                                                         |
| [`drop_collection`](#fiftyone.core.odm.document.DynamicDocument.drop_collection)()                            | Drops the entire collection associated with this `Document` type from the database.                                                                                                              |
| [`ensure_indexes`](#fiftyone.core.odm.document.DynamicDocument.ensure_indexes)()                              | Checks the document meta data and ensures all the indexes exist.                                                                                                                                 |
| [`fancy_repr`](#fiftyone.core.odm.document.DynamicDocument.fancy_repr)([class_name, select_fields, ...])      | Generates a customizable string representation of the document.                                                                                                                                  |
| [`field_to_mongo`](#fiftyone.core.odm.document.DynamicDocument.field_to_mongo)(field_name)                    |                                                                                                                                                                                                  |
| [`field_to_python`](#fiftyone.core.odm.document.DynamicDocument.field_to_python)(field_name, value)           |                                                                                                                                                                                                  |
| [`from_dict`](#fiftyone.core.odm.document.DynamicDocument.from_dict)(d[, extended])                           | Loads the document from a BSON/JSON dictionary.                                                                                                                                                  |
| [`from_json`](#fiftyone.core.odm.document.DynamicDocument.from_json)(s)                                       | Loads the document from a JSON string.                                                                                                                                                           |
| [`get_field`](#fiftyone.core.odm.document.DynamicDocument.get_field)(field_name)                              | Gets the field of the document.                                                                                                                                                                  |
| [`get_text_score`](#fiftyone.core.odm.document.DynamicDocument.get_text_score)()                              | Get text score from text query                                                                                                                                                                   |
| [`has_field`](#fiftyone.core.odm.document.DynamicDocument.has_field)(field_name)                              | Determines whether the document has a field of the given name.                                                                                                                                   |
| [`iter_fields`](#fiftyone.core.odm.document.DynamicDocument.iter_fields)()                                    | Returns an iterator over the `(name, value)` pairs of the public fields of the document.                                                                                                         |
| [`list_indexes`](#fiftyone.core.odm.document.DynamicDocument.list_indexes)()                                  | Lists all indexes that should be created for the Document collection.                                                                                                                            |
| [`merge`](#fiftyone.core.odm.document.DynamicDocument.merge)(doc[, merge_lists, merge_dicts, overwrite])      | Merges the contents of the given document into this document.                                                                                                                                    |
| [`modify`](#fiftyone.core.odm.document.DynamicDocument.modify)([query])                                       | Perform an atomic update of the document in the database and reload the document object using updated version.                                                                                   |
| [`register_delete_rule`](#fiftyone.core.odm.document.DynamicDocument.register_delete_rule)(document_cls, ...) | This method registers the delete rules to apply when removing this object.                                                                                                                       |
| [`reload`](#fiftyone.core.odm.document.DynamicDocument.reload)(\*fields, \*\*kwargs)                          | Reloads all attributes from the database.                                                                                                                                                        |
| [`save`](#fiftyone.core.odm.document.DynamicDocument.save)([force_insert, validate, clean, ...])              | Save the `Document` to the database.                                                                                                                                                             |
| [`select_related`](#fiftyone.core.odm.document.DynamicDocument.select_related)([max_depth])                   | Handles dereferencing of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) objects to a maximum depth in order to cut down the number queries to mongodb. |
| [`set_field`](#fiftyone.core.odm.document.DynamicDocument.set_field)(field_name, value[, create])             | Sets the value of a field of the document.                                                                                                                                                       |
| [`switch_collection`](#fiftyone.core.odm.document.DynamicDocument.switch_collection)(collection_name[, ...])  | Temporarily switch the collection for a document instance.                                                                                                                                       |
| [`switch_db`](#fiftyone.core.odm.document.DynamicDocument.switch_db)(db_alias[, keep_created])                | Temporarily switch the database for a document instance.                                                                                                                                         |
| [`to_dbref`](#fiftyone.core.odm.document.DynamicDocument.to_dbref)()                                          | Returns an instance of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) useful in `__raw__` queries.                                                     |
| [`to_dict`](#fiftyone.core.odm.document.DynamicDocument.to_dict)([extended])                                  | Serializes this document to a BSON/JSON dictionary.                                                                                                                                              |
| [`to_json`](#fiftyone.core.odm.document.DynamicDocument.to_json)([pretty_print])                              | Serializes the document to a JSON string.                                                                                                                                                        |
| [`to_mongo`](#fiftyone.core.odm.document.DynamicDocument.to_mongo)(\*args, \*\*kwargs)                        | Return as SON data ready for use with MongoDB.                                                                                                                                                   |
| [`update`](#fiftyone.core.odm.document.DynamicDocument.update)(\*\*kwargs)                                    | Performs an update on the `Document` A convenience wrapper to `update()`.                                                                                                                        |
| [`validate`](#fiftyone.core.odm.document.DynamicDocument.validate)([clean])                                   | Ensure that all fields' values are valid and that required fields are present.                                                                                                                   |

**Classes:**

| [`my_metaclass`](#fiftyone.core.odm.document.DynamicDocument.my_metaclass)   |    |
|------------------------------------------------------------------------------|----|

#### STRICT *= False*

#### cascade_save(\*\*kwargs)

Recursively save any references and generic references on the
document.

#### clean()

Hook for doing document level data cleaning (usually validation or assignment)
before validation is run.

Any ValidationError raised by this method will not be associated with
a particular field; it will have a special-case association with the
field defined by NON_FIELD_ERRORS.

#### clear_field(field_name)

Clears the field from the document.

* **Parameters:**
  **field_name** – the field name
* **Raises:**
  **ValueError** – if the field does not exist

#### *classmethod* compare_indexes()

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

#### copy()

Returns a deep copy of the document.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

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

Creates the given indexes if required.

* **Parameters:**
  * **keys** – 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
  * **background** – Allows index creation in the background

#### delete(signal_kwargs=None, \*\*write_concern)

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

* **Parameters:**
  * **signal_kwargs** – (optional) kwargs dictionary to be passed to
    the signal calls.
  * **write_concern** – Extra keyword arguments are passed down which
    will be used as options for the resultant `getLastError` command.
    For example, `save(..., 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.

Raises `OperationError` if the document has no collection set
(i.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 - see guide/defining-documents

By default, this will get called automatically upon first interaction with the
Document collection (query, save, etc) so unless you disabled `auto_create_index`, you
shouldn’t have to call this manually.

This also gets called upon every call to Document.save if `auto_create_index_on_save` is set to True

If called multiple times, MongoDB will not re-recreate indexes if they exist already

#### NOTE
You can disable automatic index creation by setting
`auto_create_index` to False in the documents meta data

#### fancy_repr(class_name=None, select_fields=None, exclude_fields=None, \*\*kwargs)

Generates a customizable string representation of the document.

* **Parameters:**
  * **class_name** (*None*) – optional class name to use
  * **select_fields** (*None*) – iterable of field names to restrict to
  * **exclude_fields** (*None*) – iterable of field names to exclude
  * **\*\*kwargs** – additional key-value pairs to include in the string
    representation
* **Returns:**
  a string representation of the document

#### *property* field_names

An ordered tuple of the public fields of this document.

#### field_to_mongo(field_name)

#### field_to_python(field_name, value)

#### *classmethod* from_dict(d, extended=False)

Loads the document from a BSON/JSON dictionary.

* **Parameters:**
  * **d** – a dictionary
  * **extended** (*False*) – whether the input dictionary may contain
    serialized extended JSON constructs
* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### get_field(field_name)

Gets the field of the document.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  the field value
* **Raises:**
  **AttributeError** – if the field does not exist

#### get_text_score()

Get text score from text query

#### has_field(field_name)

Determines whether the document has a field of the given name.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  True/False

#### *property* in_db

Whether the document has been inserted into the database.

#### iter_fields()

Returns an iterator over the `(name, value)` pairs of the
public fields of the document.

* **Returns:**
  an iterator that emits `(name, value)` tuples

#### *classmethod* list_indexes()

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

Note that it will only return the indexes’ fields, not the indexes’ options

#### merge(doc, merge_lists=True, merge_dicts=True, overwrite=True)

Merges the contents of the given document into this document.

* **Parameters:**
  * **doc** – a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) of same type as this document
  * **merge_lists** (*True*) – whether to merge the elements of top-level list
    fields rather than treating the list as a single value
  * **merge_dicts** (*True*) – whether to recursively merge the contents of
    top-level dict fields rather than treating the dict as a single
    value
  * **overwrite** (*True*) – whether to overwrite (True) or skip (False)
    existing fields

#### 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.

#### NOTE
All unsaved changes that have been made to the document are
rejected if the method returns True.

* **Parameters:**
  * **query** – the update will be performed only if the document in the
    database matches the query
  * **update** – Django-style update keyword arguments

#### my_metaclass

alias of `TopLevelDocumentMetaclass`

#### *property* 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.

* **Parameters:**
  * **fields** – (optional) args list of fields to reload
  * **max_depth** – (optional) depth of dereferencing to follow

#### 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.

* **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()` OR
    `insert()`
    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.
  * **cascade** – Sets the flag for cascading saves.  You can set a
    default by setting “cascade” in the document \_\_meta_\_
  * **cascade_kwargs** – (optional) kwargs dictionary to be passed throw
    to cascading saves.  Implies `cascade=True`.
  * **\_refs** – A list of processed references used in cascading saves
  * **save_condition** – only perform save if matching record in db
    satisfies condition(s) (e.g. version number).
    Raises `OperationError` if the conditions are not satisfied
  * **signal_kwargs** – (optional) kwargs dictionary to be passed to
    the signal calls.

#### Versionchanged
Changed in version 0.5: In existing documents it only saves changed fields using
set / unset.  Saves are cascaded and any
[`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) objects that have changes are
saved as well.

#### Versionchanged
Changed in version 0.6: Added cascading saves

#### Versionchanged
Changed in version 0.8: Cascade saves are optional and default to False.  If you want
fine grain control then you can turn off using document
meta[‘cascade’] = True.  Also you can pass different kwargs to
the cascade save using cascade_kwargs which overwrites the
existing kwargs with custom values.

#### Versionchanged
Changed in version 0.26: save() no longer calls `ensure_indexes()`
unless `meta['auto_create_index_on_save']` is set to True.

#### select_related(max_depth=1)

Handles dereferencing of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) objects to
a maximum depth in order to cut down the number queries to mongodb.

#### set_field(field_name, value, create=True)

Sets the value of a field of the document.

* **Parameters:**
  * **field_name** – the field name
  * **value** – the field value
  * **create** (*True*) – whether to create the field if it does not exist
* **Raises:**
  **ValueError** – if `field_name` is not an allowed field name or does
      not exist and `create == False`

#### switch_collection(collection_name, keep_created=True)

Temporarily switch the collection for a document instance.

Only really useful for archiving off data and calling `save()`:

```default
user = User.objects.get(id=user_id)
user.switch_collection('old-users')
user.save()
```

* **Parameters:**
  * **collection_name** (*str*) – The database alias to use for saving the
    document
  * **keep_created** ([*bool*](fiftyone.core.stages.md#fiftyone.core.stages.Exists.bool)) – keep self._created value after switching collection, else is reset to True

#### SEE ALSO
Use `switch_db`
if you need to read from another database

#### switch_db(db_alias, keep_created=True)

Temporarily switch the database for a document instance.

Only really useful for archiving off data and calling `save()`:

```default
user = User.objects.get(id=user_id)
user.switch_db('archive-db')
user.save()
```

* **Parameters:**
  * **db_alias** (*str*) – The database alias to use for saving the document
  * **keep_created** ([*bool*](fiftyone.core.stages.md#fiftyone.core.stages.Exists.bool)) – keep self._created value after switching db, else is reset to True

#### SEE ALSO
Use `switch_collection`
if you need to read from another collection

#### to_dbref()

Returns an instance of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) useful in
`__raw__` queries.

#### to_dict(extended=False)

Serializes this document to a BSON/JSON dictionary.

* **Parameters:**
  **extended** (*False*) – whether to serialize extended JSON constructs
  such as ObjectIDs, Binary, etc. into JSON format
* **Returns:**
  a dict

#### to_json(pretty_print=False)

Serializes the document to a JSON string.

* **Parameters:**
  **pretty_print** (*False*) – whether to render the JSON in human readable
  format with newlines and indentations
* **Returns:**
  a JSON string

#### to_mongo(\*args, \*\*kwargs)

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* fiftyone.core.odm.document.Document(\*\*kwargs)

Bases: [`BaseDocument`](#fiftyone.core.odm.document.BaseDocument), `Document`

Base class for documents that are stored in a MongoDB collection.

The ID of a document is automatically populated when it is added to the
database, and the ID of a document is `None` if it has not been added to
the database.

#### id

the ID of the document, or `None` if it has not been added to the
database

**Methods:**

| [`copy`](#fiftyone.core.odm.document.Document.copy)([new_id])                                          | Returns a deep copy of the document.                                                                                                                                                             |
|--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`reload`](#fiftyone.core.odm.document.Document.reload)(\*fields, \*\*kwargs)                          | Reloads the document from the database.                                                                                                                                                          |
| [`save`](#fiftyone.core.odm.document.Document.save)([upsert, validate, safe])                          | Saves the document to the database.                                                                                                                                                              |
| [`copy_with_new_id`](#fiftyone.core.odm.document.Document.copy_with_new_id)()                          |                                                                                                                                                                                                  |
| [`cascade_save`](#fiftyone.core.odm.document.Document.cascade_save)(\*\*kwargs)                        | Recursively save any references and generic references on the document.                                                                                                                          |
| [`clean`](#fiftyone.core.odm.document.Document.clean)()                                                | Hook for doing document level data cleaning (usually validation or assignment) before validation is run.                                                                                         |
| [`clear_field`](#fiftyone.core.odm.document.Document.clear_field)(field_name)                          | Clears the field from the document.                                                                                                                                                              |
| [`compare_indexes`](#fiftyone.core.odm.document.Document.compare_indexes)()                            | Compares the indexes defined in MongoEngine with the ones existing in the database.                                                                                                              |
| [`create_index`](#fiftyone.core.odm.document.Document.create_index)(keys[, background])                | Creates the given indexes if required.                                                                                                                                                           |
| [`delete`](#fiftyone.core.odm.document.Document.delete)([signal_kwargs])                               | Delete the `Document` from the database.                                                                                                                                                         |
| [`drop_collection`](#fiftyone.core.odm.document.Document.drop_collection)()                            | Drops the entire collection associated with this `Document` type from the database.                                                                                                              |
| [`ensure_indexes`](#fiftyone.core.odm.document.Document.ensure_indexes)()                              | Checks the document meta data and ensures all the indexes exist.                                                                                                                                 |
| [`fancy_repr`](#fiftyone.core.odm.document.Document.fancy_repr)([class_name, select_fields, ...])      | Generates a customizable string representation of the document.                                                                                                                                  |
| [`field_to_mongo`](#fiftyone.core.odm.document.Document.field_to_mongo)(field_name)                    |                                                                                                                                                                                                  |
| [`field_to_python`](#fiftyone.core.odm.document.Document.field_to_python)(field_name, value)           |                                                                                                                                                                                                  |
| [`from_dict`](#fiftyone.core.odm.document.Document.from_dict)(d[, extended])                           | Loads the document from a BSON/JSON dictionary.                                                                                                                                                  |
| [`from_json`](#fiftyone.core.odm.document.Document.from_json)(s)                                       | Loads the document from a JSON string.                                                                                                                                                           |
| [`get_field`](#fiftyone.core.odm.document.Document.get_field)(field_name)                              | Gets the field of the document.                                                                                                                                                                  |
| [`get_text_score`](#fiftyone.core.odm.document.Document.get_text_score)()                              | Get text score from text query                                                                                                                                                                   |
| [`has_field`](#fiftyone.core.odm.document.Document.has_field)(field_name)                              | Determines whether the document has a field of the given name.                                                                                                                                   |
| [`iter_fields`](#fiftyone.core.odm.document.Document.iter_fields)()                                    | Returns an iterator over the `(name, value)` pairs of the public fields of the document.                                                                                                         |
| [`list_indexes`](#fiftyone.core.odm.document.Document.list_indexes)()                                  | Lists all indexes that should be created for the Document collection.                                                                                                                            |
| [`merge`](#fiftyone.core.odm.document.Document.merge)(doc[, merge_lists, merge_dicts, overwrite])      | Merges the contents of the given document into this document.                                                                                                                                    |
| [`modify`](#fiftyone.core.odm.document.Document.modify)([query])                                       | Perform an atomic update of the document in the database and reload the document object using updated version.                                                                                   |
| [`register_delete_rule`](#fiftyone.core.odm.document.Document.register_delete_rule)(document_cls, ...) | This method registers the delete rules to apply when removing this object.                                                                                                                       |
| [`select_related`](#fiftyone.core.odm.document.Document.select_related)([max_depth])                   | Handles dereferencing of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) objects to a maximum depth in order to cut down the number queries to mongodb. |
| [`set_field`](#fiftyone.core.odm.document.Document.set_field)(field_name, value[, create])             | Sets the value of a field of the document.                                                                                                                                                       |
| [`switch_collection`](#fiftyone.core.odm.document.Document.switch_collection)(collection_name[, ...])  | Temporarily switch the collection for a document instance.                                                                                                                                       |
| [`switch_db`](#fiftyone.core.odm.document.Document.switch_db)(db_alias[, keep_created])                | Temporarily switch the database for a document instance.                                                                                                                                         |
| [`to_dbref`](#fiftyone.core.odm.document.Document.to_dbref)()                                          | Returns an instance of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) useful in `__raw__` queries.                                                     |
| [`to_dict`](#fiftyone.core.odm.document.Document.to_dict)([extended])                                  | Serializes this document to a BSON/JSON dictionary.                                                                                                                                              |
| [`to_json`](#fiftyone.core.odm.document.Document.to_json)([pretty_print])                              | Serializes the document to a JSON string.                                                                                                                                                        |
| [`to_mongo`](#fiftyone.core.odm.document.Document.to_mongo)(\*args, \*\*kwargs)                        | Return as SON data ready for use with MongoDB.                                                                                                                                                   |
| [`update`](#fiftyone.core.odm.document.Document.update)(\*\*kwargs)                                    | Performs an update on the `Document` A convenience wrapper to `update()`.                                                                                                                        |
| [`validate`](#fiftyone.core.odm.document.Document.validate)([clean])                                   | Ensure that all fields' values are valid and that required fields are present.                                                                                                                   |

**Attributes:**

| [`STRICT`](#fiftyone.core.odm.document.Document.STRICT)           |                                                           |
|-------------------------------------------------------------------|-----------------------------------------------------------|
| [`field_names`](#fiftyone.core.odm.document.Document.field_names) | An ordered tuple of the public fields of this document.   |
| [`in_db`](#fiftyone.core.odm.document.Document.in_db)             | Whether the document has been inserted into the database. |
| [`pk`](#fiftyone.core.odm.document.Document.pk)                   | Get the primary key.                                      |

**Classes:**

| [`my_metaclass`](#fiftyone.core.odm.document.Document.my_metaclass)   |    |
|-----------------------------------------------------------------------|----|

#### copy(new_id=False)

Returns a deep copy of the document.

* **Parameters:**
  **new_id** (*False*) – whether to generate a new ID for the copied
  document. By default, the ID is left as `None` and will be
  automatically populated when the document is added to the
  database

#### reload(\*fields, \*\*kwargs)

Reloads the document from the database.

* **Parameters:**
  **\*fields** – an optional args list of specific fields to reload

#### save(upsert=False, validate=True, safe=False, \*\*kwargs)

Saves the document to the database.

If the document already exists, it will be updated, otherwise it will
be created.

* **Parameters:**
  * **upsert** (*False*) – whether to insert the document if it has an `id`
    populated but no document with that ID exists in the database
  * **validate** (*True*) – whether to validate the document
  * **safe** (*False*) – whether to `reload()` the document before raising
    any errors
* **Returns:**
  self

#### copy_with_new_id()

#### STRICT *= False*

#### cascade_save(\*\*kwargs)

Recursively save any references and generic references on the
document.

#### clean()

Hook for doing document level data cleaning (usually validation or assignment)
before validation is run.

Any ValidationError raised by this method will not be associated with
a particular field; it will have a special-case association with the
field defined by NON_FIELD_ERRORS.

#### clear_field(field_name)

Clears the field from the document.

* **Parameters:**
  **field_name** – the field name
* **Raises:**
  **ValueError** – if the field does not exist

#### *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.

* **Parameters:**
  * **keys** – 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
  * **background** – Allows index creation in the background

#### delete(signal_kwargs=None, \*\*write_concern)

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

* **Parameters:**
  * **signal_kwargs** – (optional) kwargs dictionary to be passed to
    the signal calls.
  * **write_concern** – Extra keyword arguments are passed down which
    will be used as options for the resultant `getLastError` command.
    For example, `save(..., 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.

Raises `OperationError` if the document has no collection set
(i.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 - see guide/defining-documents

By default, this will get called automatically upon first interaction with the
Document collection (query, save, etc) so unless you disabled `auto_create_index`, you
shouldn’t have to call this manually.

This also gets called upon every call to Document.save if `auto_create_index_on_save` is set to True

If called multiple times, MongoDB will not re-recreate indexes if they exist already

#### NOTE
You can disable automatic index creation by setting
`auto_create_index` to False in the documents meta data

#### fancy_repr(class_name=None, select_fields=None, exclude_fields=None, \*\*kwargs)

Generates a customizable string representation of the document.

* **Parameters:**
  * **class_name** (*None*) – optional class name to use
  * **select_fields** (*None*) – iterable of field names to restrict to
  * **exclude_fields** (*None*) – iterable of field names to exclude
  * **\*\*kwargs** – additional key-value pairs to include in the string
    representation
* **Returns:**
  a string representation of the document

#### *property* field_names

An ordered tuple of the public fields of this document.

#### field_to_mongo(field_name)

#### field_to_python(field_name, value)

#### *classmethod* from_dict(d, extended=False)

Loads the document from a BSON/JSON dictionary.

* **Parameters:**
  * **d** – a dictionary
  * **extended** (*False*) – whether the input dictionary may contain
    serialized extended JSON constructs
* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument)

#### get_field(field_name)

Gets the field of the document.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  the field value
* **Raises:**
  **AttributeError** – if the field does not exist

#### get_text_score()

Get text score from text query

#### has_field(field_name)

Determines whether the document has a field of the given name.

* **Parameters:**
  **field_name** – the field name
* **Returns:**
  True/False

#### *property* in_db

Whether the document has been inserted into the database.

#### iter_fields()

Returns an iterator over the `(name, value)` pairs of the
public fields of the document.

* **Returns:**
  an iterator that emits `(name, value)` tuples

#### *classmethod* list_indexes()

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

Note that it will only return the indexes’ fields, not the indexes’ options

#### merge(doc, merge_lists=True, merge_dicts=True, overwrite=True)

Merges the contents of the given document into this document.

* **Parameters:**
  * **doc** – a [`SerializableDocument`](#fiftyone.core.odm.document.SerializableDocument) of same type as this document
  * **merge_lists** (*True*) – whether to merge the elements of top-level list
    fields rather than treating the list as a single value
  * **merge_dicts** (*True*) – whether to recursively merge the contents of
    top-level dict fields rather than treating the dict as a single
    value
  * **overwrite** (*True*) – whether to overwrite (True) or skip (False)
    existing fields

#### 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.

#### NOTE
All unsaved changes that have been made to the document are
rejected if the method returns True.

* **Parameters:**
  * **query** – the update will be performed only if the document in the
    database matches the query
  * **update** – Django-style update keyword arguments

#### my_metaclass

alias of `TopLevelDocumentMetaclass`

#### *property* 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.

#### select_related(max_depth=1)

Handles dereferencing of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) objects to
a maximum depth in order to cut down the number queries to mongodb.

#### set_field(field_name, value, create=True)

Sets the value of a field of the document.

* **Parameters:**
  * **field_name** – the field name
  * **value** – the field value
  * **create** (*True*) – whether to create the field if it does not exist
* **Raises:**
  **ValueError** – if `field_name` is not an allowed field name or does
      not exist and `create == False`

#### switch_collection(collection_name, keep_created=True)

Temporarily switch the collection for a document instance.

Only really useful for archiving off data and calling `save()`:

```default
user = User.objects.get(id=user_id)
user.switch_collection('old-users')
user.save()
```

* **Parameters:**
  * **collection_name** (*str*) – The database alias to use for saving the
    document
  * **keep_created** ([*bool*](fiftyone.core.stages.md#fiftyone.core.stages.Exists.bool)) – keep self._created value after switching collection, else is reset to True

#### SEE ALSO
Use `switch_db`
if you need to read from another database

#### switch_db(db_alias, keep_created=True)

Temporarily switch the database for a document instance.

Only really useful for archiving off data and calling `save()`:

```default
user = User.objects.get(id=user_id)
user.switch_db('archive-db')
user.save()
```

* **Parameters:**
  * **db_alias** (*str*) – The database alias to use for saving the document
  * **keep_created** ([*bool*](fiftyone.core.stages.md#fiftyone.core.stages.Exists.bool)) – keep self._created value after switching db, else is reset to True

#### SEE ALSO
Use `switch_collection`
if you need to read from another collection

#### to_dbref()

Returns an instance of [`DBRef`](https://pymongo.readthedocs.io/en/stable/api/bson/dbref.html#bson.dbref.DBRef) useful in
`__raw__` queries.

#### to_dict(extended=False)

Serializes this document to a BSON/JSON dictionary.

* **Parameters:**
  **extended** (*False*) – whether to serialize extended JSON constructs
  such as ObjectIDs, Binary, etc. into JSON format
* **Returns:**
  a dict

#### to_json(pretty_print=False)

Serializes the document to a JSON string.

* **Parameters:**
  **pretty_print** (*False*) – whether to render the JSON in human readable
  format with newlines and indentations
* **Returns:**
  a JSON string

#### to_mongo(\*args, \*\*kwargs)

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.
