API Reference

Beanie

Async MongoDB ODM for Python built on Motor and Pydantic, offering typed documents and query APIs for FastAPI.

Official Documentation ↗
CompatibilityThis documentation covers version v2.2.0. Check the official docs for the latest API surface.

Installation

pippip install beanie

Methods

Overview

Beanie is an async MongoDB ODM for Python built on Motor and Pydantic, giving typed documents and query APIs suited to FastAPI. This reference lists the most frequently used APIs with accurate signatures and runnable snippets.

Core APIs

  • init_beanie — Binds document classes to a Motor database and prepares indexes.
  • Document.insert — Inserts the document instance into its collection and returns it with an id.
  • Document.find — Queries documents with chained filters, sorting, and pagination.

Example

from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient("mongodb://localhost:27017")
await init_beanie(database=client.app, document_models=[User])

Notes

It requires an async context, so use it inside an event loop. Pydantic validation runs on model construction, catching shape errors early.

Verification

Insert a document and confirm the returned instance has a generated id, then find it back by a field filter.

FAQ

How does Beanie validate documents?
It builds on Pydantic, so field types and validators run on model construction and on query results.
What driver does Beanie use?
It uses Motor, the async MongoDB driver, so all database calls are awaitable within an event loop.
How do I declare indexes?
Set an Indexed field or list them in the Settings inner class so Beanie ensures them at init_beanie.