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

# fiftyone.core.odm.ontology

Ontology documents.

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

**Classes:**

| [`OntologyType`](#fiftyone.core.odm.ontology.OntologyType)(\*values)           | Allowed values for [`OntologyDocument.type`](#fiftyone.core.odm.ontology.OntologyDocument.type) in storage and APIs.   |
|--------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| [`OntologyDocument`](#fiftyone.core.odm.ontology.OntologyDocument)(\*\*kwargs) | Backing document for ontologies.                                                                                       |

### *class* fiftyone.core.odm.ontology.OntologyType(\*values)

Bases: `str`, `Enum`

Allowed values for [`OntologyDocument.type`](#fiftyone.core.odm.ontology.OntologyDocument.type) in storage and APIs.

`TAXONOMY` — a reusable hierarchical class tree. Multiple annotation
ontologies can reference the same taxonomy by name.

`ANNOTATION_ONTOLOGY` — a container that defines classes, attributes
(with optional conditional display logic), and an optional reference to
a bundled taxonomy. This is the document that gets connected to a
label schema on a field.

**Attributes:**

| [`TAXONOMY`](#fiftyone.core.odm.ontology.OntologyType.TAXONOMY)                       |    |
|---------------------------------------------------------------------------------------|----|
| [`ANNOTATION_ONTOLOGY`](#fiftyone.core.odm.ontology.OntologyType.ANNOTATION_ONTOLOGY) |    |

**Methods:**

| [`encode`](#fiftyone.core.odm.ontology.OntologyType.encode)([encoding, errors])     | Encode the string using the codec registered for encoding.                                                  |
|-------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|
| [`replace`](#fiftyone.core.odm.ontology.OntologyType.replace)(old, new, /[, count]) | Return a copy with all occurrences of substring old replaced by new.                                        |
| [`split`](#fiftyone.core.odm.ontology.OntologyType.split)([sep, maxsplit])          | Return a list of the substrings in the string, using sep as the separator string.                           |
| [`rsplit`](#fiftyone.core.odm.ontology.OntologyType.rsplit)([sep, maxsplit])        | Return a list of the substrings in the string, using sep as the separator string.                           |
| [`join`](#fiftyone.core.odm.ontology.OntologyType.join)(iterable, /)                | Concatenate any number of strings.                                                                          |
| [`capitalize`](#fiftyone.core.odm.ontology.OntologyType.capitalize)()               | Return a capitalized version of the string.                                                                 |
| [`casefold`](#fiftyone.core.odm.ontology.OntologyType.casefold)()                   | Return a version of the string suitable for caseless comparisons.                                           |
| [`title`](#fiftyone.core.odm.ontology.OntologyType.title)()                         | Return a version of the string where each word is titlecased.                                               |
| [`center`](#fiftyone.core.odm.ontology.OntologyType.center)(width[, fillchar])      | Return a centered string of length width.                                                                   |
| [`count`](#fiftyone.core.odm.ontology.OntologyType.count)                           | Return the number of non-overlapping occurrences of substring sub in string S[start:end].                   |
| [`expandtabs`](#fiftyone.core.odm.ontology.OntologyType.expandtabs)([tabsize])      | Return a copy where all tab characters are expanded using spaces.                                           |
| [`find`](#fiftyone.core.odm.ontology.OntologyType.find)                             | Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].  |
| [`partition`](#fiftyone.core.odm.ontology.OntologyType.partition)(sep, /)           | Partition the string into three parts using the given separator.                                            |
| [`index`](#fiftyone.core.odm.ontology.OntologyType.index)                           | Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].  |
| [`ljust`](#fiftyone.core.odm.ontology.OntologyType.ljust)(width[, fillchar])        | Return a left-justified string of length width.                                                             |
| [`lower`](#fiftyone.core.odm.ontology.OntologyType.lower)()                         | Return a copy of the string converted to lowercase.                                                         |
| [`lstrip`](#fiftyone.core.odm.ontology.OntologyType.lstrip)([chars])                | Return a copy of the string with leading whitespace removed.                                                |
| [`rfind`](#fiftyone.core.odm.ontology.OntologyType.rfind)                           | Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. |
| [`rindex`](#fiftyone.core.odm.ontology.OntologyType.rindex)                         | Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. |
| [`rjust`](#fiftyone.core.odm.ontology.OntologyType.rjust)(width[, fillchar])        | Return a right-justified string of length width.                                                            |
| [`rstrip`](#fiftyone.core.odm.ontology.OntologyType.rstrip)([chars])                | Return a copy of the string with trailing whitespace removed.                                               |
| [`rpartition`](#fiftyone.core.odm.ontology.OntologyType.rpartition)(sep, /)         | Partition the string into three parts using the given separator.                                            |
| [`splitlines`](#fiftyone.core.odm.ontology.OntologyType.splitlines)([keepends])     | Return a list of the lines in the string, breaking at line boundaries.                                      |
| [`strip`](#fiftyone.core.odm.ontology.OntologyType.strip)([chars])                  | Return a copy of the string with leading and trailing whitespace removed.                                   |
| [`swapcase`](#fiftyone.core.odm.ontology.OntologyType.swapcase)()                   | Convert uppercase characters to lowercase and lowercase characters to uppercase.                            |
| [`translate`](#fiftyone.core.odm.ontology.OntologyType.translate)(table, /)         | Replace each character in the string using the given translation table.                                     |
| [`upper`](#fiftyone.core.odm.ontology.OntologyType.upper)()                         | Return a copy of the string converted to uppercase.                                                         |
| [`startswith`](#fiftyone.core.odm.ontology.OntologyType.startswith)                 | Return True if the string starts with the specified prefix, False otherwise.                                |
| [`endswith`](#fiftyone.core.odm.ontology.OntologyType.endswith)                     | Return True if the string ends with the specified suffix, False otherwise.                                  |
| [`removeprefix`](#fiftyone.core.odm.ontology.OntologyType.removeprefix)(prefix, /)  | Return a str with the given prefix string removed if present.                                               |
| [`removesuffix`](#fiftyone.core.odm.ontology.OntologyType.removesuffix)(suffix, /)  | Return a str with the given suffix string removed if present.                                               |
| [`isascii`](#fiftyone.core.odm.ontology.OntologyType.isascii)()                     | Return True if all characters in the string are ASCII, False otherwise.                                     |
| [`islower`](#fiftyone.core.odm.ontology.OntologyType.islower)()                     | Return True if the string is a lowercase string, False otherwise.                                           |
| [`isupper`](#fiftyone.core.odm.ontology.OntologyType.isupper)()                     | Return True if the string is an uppercase string, False otherwise.                                          |
| [`istitle`](#fiftyone.core.odm.ontology.OntologyType.istitle)()                     | Return True if the string is a title-cased string, False otherwise.                                         |
| [`isspace`](#fiftyone.core.odm.ontology.OntologyType.isspace)()                     | Return True if the string is a whitespace string, False otherwise.                                          |
| [`isdecimal`](#fiftyone.core.odm.ontology.OntologyType.isdecimal)()                 | Return True if the string is a decimal string, False otherwise.                                             |
| [`isdigit`](#fiftyone.core.odm.ontology.OntologyType.isdigit)()                     | Return True if the string is a digit string, False otherwise.                                               |
| [`isnumeric`](#fiftyone.core.odm.ontology.OntologyType.isnumeric)()                 | Return True if the string is a numeric string, False otherwise.                                             |
| [`isalpha`](#fiftyone.core.odm.ontology.OntologyType.isalpha)()                     | Return True if the string is an alphabetic string, False otherwise.                                         |
| [`isalnum`](#fiftyone.core.odm.ontology.OntologyType.isalnum)()                     | Return True if the string is an alpha-numeric string, False otherwise.                                      |
| [`isidentifier`](#fiftyone.core.odm.ontology.OntologyType.isidentifier)()           | Return True if the string is a valid Python identifier, False otherwise.                                    |
| [`isprintable`](#fiftyone.core.odm.ontology.OntologyType.isprintable)()             | Return True if all characters in the string are printable, False otherwise.                                 |
| [`zfill`](#fiftyone.core.odm.ontology.OntologyType.zfill)(width, /)                 | Pad a numeric string with zeros on the left, to fill a field of the given width.                            |
| [`format`](#fiftyone.core.odm.ontology.OntologyType.format)(\*args, \*\*kwargs)     | Return a formatted version of the string, using substitutions from args and kwargs.                         |
| [`format_map`](#fiftyone.core.odm.ontology.OntologyType.format_map)(mapping, /)     | Return a formatted version of the string, using substitutions from mapping.                                 |
| [`maketrans`](#fiftyone.core.odm.ontology.OntologyType.maketrans)                   | Return a translation table usable for str.translate().                                                      |

#### TAXONOMY *= 'taxonomy'*

#### ANNOTATION_ONTOLOGY *= 'annotation_ontology'*

#### encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding
: The encoding in which to encode the string.

errors
: The error handling scheme to use for encoding errors.
  The default is ‘strict’ meaning that encoding errors raise a
  UnicodeEncodeError.  Other possible values are ‘ignore’, ‘replace’
  and ‘xmlcharrefreplace’ as well as any other name registered with
  codecs.register_error that can handle UnicodeEncodeErrors.

#### replace(old, new, , count=-1)

Return a copy with all occurrences of substring old replaced by new.

> count
> : Maximum number of occurrences to replace.
>   -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are
replaced.

#### split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

> sep
> : The separator used to split the string.
>   <br/>
>   When set to None (the default value), will split on any
>   whitespace character (including n r t f and spaces) and
>   will discard empty strings from the result.

> maxsplit
> : Maximum number of splits.
>   -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been
intentionally delimited.  With natural text that includes
punctuation, consider using the regular expression module.

#### rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

> sep
> : The separator used to split the string.
>   <br/>
>   When set to None (the default value), will split on any
>   whitespace character (including n r t f and spaces) and
>   will discard empty strings from the result.

> maxsplit
> : Maximum number of splits.
>   -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

#### join(iterable,)

Concatenate any number of strings.

The string whose method is called is inserted in between each given
string.  The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

#### capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the
rest lower case.

#### casefold()

Return a version of the string suitable for caseless comparisons.

#### title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all
remaining cased characters have lower case.

#### center(width, fillchar=' ',)

Return a centered string of length width.

Padding is done using the specified fill character (default is
a space).

#### count()

Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Optional arguments start and end are interpreted as in slice
notation.

#### expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

#### find()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice
notation.  Return -1 on failure.

#### partition(sep,)

Partition the string into three parts using the given separator.

This will search for the separator in the string.  If the separator
is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing
the original string and two empty strings.

#### index()

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice
notation.  Raises ValueError when the substring is not found.

#### ljust(width, fillchar=' ',)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is
a space).

#### lower()

Return a copy of the string converted to lowercase.

#### lstrip(chars=None,)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

#### rfind()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice
notation.  Return -1 on failure.

#### rindex()

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].

Optional arguments start and end are interpreted as in slice
notation.  Raises ValueError when the substring is not found.

#### rjust(width, fillchar=' ',)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is
a space).

#### rstrip(chars=None,)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#### rpartition(sep,)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the
end.  If the separator is found, returns a 3-tuple containing the
part before the separator, the separator itself, and the part after
it.

If the separator is not found, returns a 3-tuple containing two
empty strings and the original string.

#### splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends
is given and true.

#### strip(chars=None,)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#### swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

#### translate(table,)

Replace each character in the string using the given translation table.

> table
> : Translation table, which must be a mapping of Unicode ordinals
>   to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via \_\_getitem_\_, for
instance a dictionary or list.  If this operation raises
LookupError, the character is left untouched.  Characters mapped to
None are deleted.

#### upper()

Return a copy of the string converted to uppercase.

#### startswith()

Return True if the string starts with the specified prefix, False otherwise.

prefix
: A string or a tuple of strings to try.

start
: Optional start position. Default: start of the string.

end
: Optional stop position. Default: end of the string.

#### endswith()

Return True if the string ends with the specified suffix, False otherwise.

suffix
: A string or a tuple of strings to try.

start
: Optional start position. Default: start of the string.

end
: Optional stop position. Default: end of the string.

#### removeprefix(prefix,)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return
string[len(prefix):].  Otherwise, return a copy of the original
string.

#### removesuffix(suffix,)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not
empty, return string[:-len(suffix)].  Otherwise, return a copy of
the original string.

#### isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F.
Empty string is ASCII too.

#### islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are
lowercase and there is at least one cased character in the string.

#### isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are
uppercase and there is at least one cased character in the string.

#### istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.

#### isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are
whitespace and there is at least one character in the string.

#### isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are
decimal and there is at least one character in the string.

#### isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are
digits and there is at least one character in the string.

#### isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and
there is at least one character in the string.

#### isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are
alphabetic and there is at least one character in the string.

#### isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are
alpha-numeric and there is at least one character in the string.

#### isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved
identifier, such as “def” or “class”.

#### isprintable()

Return True if all characters in the string are printable, False otherwise.

A character is printable if repr() may use it in its output.

#### zfill(width,)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

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

Return a formatted version of the string, using substitutions from args and kwargs.
The substitutions are identified by braces (‘{’ and ‘}’).

#### format_map(mapping,)

Return a formatted version of the string, using substitutions from mapping.
The substitutions are identified by braces (‘{’ and ‘}’).

#### *static* maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping
Unicode ordinals (integers) or characters to Unicode ordinals,
strings or None.  Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length,
and in the resulting dictionary, each character in x will be mapped
to the character at the same position in y.  If there is a third
argument, it must be a string, whose characters will be mapped to
None in the result.

### *class* fiftyone.core.odm.ontology.OntologyDocument(\*\*kwargs)

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

Backing document for ontologies.

Ontologies are global resources not scoped to any single dataset.
Multiple datasets can reference the same ontology by name. Each
save creates a new versioned document; `(slug, version)` is unique,
so names differing only in case or punctuation collide on save.

`schema_version` records the internal layout version of the row at
write time. Bump `CURRENT_SCHEMA_VERSION` and add a migration when
changing the persisted structure (especially `root`).

**Attributes:**

| [`name`](#fiftyone.core.odm.ontology.OntologyDocument.name)                         | A unicode string field.                                     |
|-------------------------------------------------------------------------------------|-------------------------------------------------------------|
| [`slug`](#fiftyone.core.odm.ontology.OntologyDocument.slug)                         | A unicode string field.                                     |
| [`version`](#fiftyone.core.odm.ontology.OntologyDocument.version)                   | A 32 bit integer field.                                     |
| [`schema_version`](#fiftyone.core.odm.ontology.OntologyDocument.schema_version)     | A 32 bit integer field.                                     |
| [`type`](#fiftyone.core.odm.ontology.OntologyDocument.type)                         | A unicode string field.                                     |
| [`description`](#fiftyone.core.odm.ontology.OntologyDocument.description)           | A unicode string field.                                     |
| [`root`](#fiftyone.core.odm.ontology.OntologyDocument.root)                         | A dictionary field that wraps a standard Python dictionary. |
| [`created_at`](#fiftyone.core.odm.ontology.OntologyDocument.created_at)             | A datetime field.                                           |
| [`last_modified_at`](#fiftyone.core.odm.ontology.OntologyDocument.last_modified_at) | A datetime field.                                           |
| [`STRICT`](#fiftyone.core.odm.ontology.OntologyDocument.STRICT)                     |                                                             |
| [`field_names`](#fiftyone.core.odm.ontology.OntologyDocument.field_names)           | An ordered tuple of the public fields of this document.     |
| [`id`](#fiftyone.core.odm.ontology.OntologyDocument.id)                             | A field wrapper around MongoDB's ObjectIds.                 |
| [`in_db`](#fiftyone.core.odm.ontology.OntologyDocument.in_db)                       | Whether the document has been inserted into the database.   |
| [`pk`](#fiftyone.core.odm.ontology.OntologyDocument.pk)                             | Get the primary key.                                        |

**Methods:**

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

**Miscellaneous:**

| [`DoesNotExist`](#fiftyone.core.odm.ontology.OntologyDocument.DoesNotExist)                       |    |
|---------------------------------------------------------------------------------------------------|----|
| [`MultipleObjectsReturned`](#fiftyone.core.odm.ontology.OntologyDocument.MultipleObjectsReturned) |    |

**Classes:**

| [`my_metaclass`](#fiftyone.core.odm.ontology.OntologyDocument.my_metaclass)   |    |
|-------------------------------------------------------------------------------|----|

#### name

A unicode string field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### slug

A unicode string field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### version

A 32 bit integer field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### schema_version

A 32 bit integer field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### type

A unicode string field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### description

A unicode string field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### root

A dictionary field that wraps a standard Python dictionary.

If this field is not set, its default value is `{}`.

* **Parameters:**
  * **field** (*None*) – an optional `Field` instance describing the type
    of the values in the dict
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### created_at

A datetime field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### last_modified_at

A datetime field.

* **Parameters:**
  * **description** (*None*) – an optional description
  * **info** (*None*) – an optional info dict
  * **read_only** (*False*) – whether the field is read-only
  * **created_at** (*None*) – the datetime the field was created

#### save(\*args: Any, \*\*kwargs: Any) → [OntologyDocument](#fiftyone.core.odm.ontology.OntologyDocument)

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

#### *exception* DoesNotExist

Bases: `DoesNotExist`

**Methods:**

| [`add_note`](#fiftyone.core.odm.ontology.OntologyDocument.DoesNotExist.add_note)(object, /)             | Exception.add_note(note) -- add a note to the exception                         |
|---------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`with_traceback`](#fiftyone.core.odm.ontology.OntologyDocument.DoesNotExist.with_traceback)(object, /) | Exception.with_traceback(tb) -- set self._\_traceback_\_ to tb and return self. |

**Attributes:**

| [`args`](#fiftyone.core.odm.ontology.OntologyDocument.DoesNotExist.args)   |    |
|----------------------------------------------------------------------------|----|

#### add_note(object,)

Exception.add_note(note) –
add a note to the exception

#### args

#### with_traceback(object,)

Exception.with_traceback(tb) –
set self._\_traceback_\_ to tb and return self.

#### *exception* MultipleObjectsReturned

Bases: `MultipleObjectsReturned`

**Methods:**

| [`add_note`](#fiftyone.core.odm.ontology.OntologyDocument.MultipleObjectsReturned.add_note)(object, /)             | Exception.add_note(note) -- add a note to the exception                         |
|--------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`with_traceback`](#fiftyone.core.odm.ontology.OntologyDocument.MultipleObjectsReturned.with_traceback)(object, /) | Exception.with_traceback(tb) -- set self._\_traceback_\_ to tb and return self. |

**Attributes:**

| [`args`](#fiftyone.core.odm.ontology.OntologyDocument.MultipleObjectsReturned.args)   |    |
|---------------------------------------------------------------------------------------|----|

#### add_note(object,)

Exception.add_note(note) –
add a note to the exception

#### args

#### with_traceback(object,)

Exception.with_traceback(tb) –
set self._\_traceback_\_ to tb and return self.

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

#### copy_with_new_id()

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

#### *classmethod* from_json(s)

Loads the document from a JSON string.

* **Returns:**
  a `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

#### id

A field wrapper around MongoDB’s ObjectIds.

#### *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` 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 the document from the database.

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

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