DEV Community

Cover image for Mongox: Familiar Python MongoDB ODM
Amin Alaee
Amin Alaee

Posted on

Mongox: Familiar Python MongoDB ODM

Mongox is a an async MongoDB ODM (Object Document Mapper)built on top of Motor and Pydantic.
Mongox has a simple syntax, is easy to pick-up for people who have experience working with Python ORMs and is fully type-annotated.

You can install the python package:

pip install mongox
Enter fullscreen mode Exit fullscreen mode

And you can define your models/collections using the Pydantic syntax:

import asyncio

import mongox

client = mongox.Client("mongodb://localhost:27017")
db = client.get_database("test_db")


class Movie(mongox.Model):
    name: str
    year: int

    class Meta:
        collection = db.get_collection("movies")
Enter fullscreen mode Exit fullscreen mode

You can now insert and query some collections:

movie = await Movie(name="Forrest Gump", year=1994).insert()
Enter fullscreen mode Exit fullscreen mode

Since Mongox is built on top of Pydantic, it plays well with Mypy and has auto-complete in IDE.

You can then query the document with:

movie = await Movie.query(Movie.name == "Forrest Gump").get()
Enter fullscreen mode Exit fullscreen mode

Or to get all collections:

movies = await Movie.query().all()
Enter fullscreen mode Exit fullscreen mode

Please visit the project page for documentation and full info here.

Discussion (0)