Skip to content

Embedded documents

Embedded documents are document to be embedded in mongoz.Document. The difference between one and the other is that the EmbeddedDocument are not inserted separately and do not have a separate _id.

To define an EmbeddedDocument you should inherit from mongoz.EmbeddedDocument and define the fields in the way you would define for any other mongoz.Document.

from typing import List

import mongoz
from mongoz import Document, EmbeddedDocument

database_uri = "mongodb://localhost:27017"
registry = mongoz.Registry(database_uri)


class Award(EmbeddedDocument):
    name: str = mongoz.String()


class Crew(EmbeddedDocument):
    award: Award = mongoz.Embed(Award)
    name: str = mongoz.String()


class Actor(EmbeddedDocument):
    name: str = mongoz.String()


class Genre(EmbeddedDocument):
    title: str = mongoz.String()


class Movie(Document):
    actors: List[Actor] = mongoz.Array(Actor)
    name: str = mongoz.String()
    director: Crew = mongoz.Embed(Crew)
    genre: Genre = mongoz.Embed(Genre)
    year: int = mongoz.Integer()

    class Meta:
        registry = registry
        database = "my_db"

As you can see, the EmbeddedDocument is not a standlone document itself but part of the document when declaring.

An EmbeddedDocument canm be used inside another and therefore creating a nested declaration when saving the results.