Contents

[beanie] Custom collection name for beanie Document models.

0
Contents

The following beanie model will result in documents being saved into a MongoDB collection named Person. What if we want our collection to be named people?

from beanie import Document, Indexed

class Person(Document):
    name = str
    email = Indexed(str, unique=True)
    age: Optiona[int]
    is_active: bool = False
    created_at: datetime
    updated_at: datetime

Beanie provides a mechanism to deal with this exact case.

Adding a Collection inner class, the name attribute tells beanie to use an alternative collection name.

from beanie import Document, Indexed

class Person(Document):
    name = str
    email = Indexed(str, unique=True)
    age: Optiona[int]
    is_active: bool = False
    created_at: datetime
    updated_at: datetime

    class Collection:
        name = "people"

In this next example, our model is named Vehicle but the Mongodb collection will be cars.

from beanie import Document, Indexed

class Vehicle(Document):
    make = str
    model = str
    year = int
    mileage: int
    condition: str

    class Collection
        name = "cars"

About beanie

Beanie - is an Asynchronous Python object-document mapper (ODM) for MongoDB, based on Motor and Pydantic.