Skip to main content

Asynchronous Python ODM for MongoDB

Project description

Beanie

Getting Started with Beanie

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

When using Beanie each database collection has a corresponding Document that is used to interact with that collection. In addition to retrieving data, Beanie allows you to add, update, or delete documents from the collection as well.

Beanie saves you time by removing boiler-plate code and it helps you focus on the parts of your app that actually matter.

Data and schema migrations are supported by Beanie out of the box.

Installation

PIP

pip install beanie

Poetry

poetry add beanie

Basic Example

Document models

from typing import Optional
from pydantic import BaseModel
from beanie import Document, Indexed


class Category(BaseModel):
    name: str
    description: str


class Product(Document):  # This is the model
    name: str
    description: Optional[str] = None
    price: Indexed(float)
    category: Category

    class Collection:
        name = "products"

Each document by default has id ObjectId field, which reflects _id MongoDB document field. It can be used later as an argument for the get() method.

More details about Documents, collections, and indexes configuration could be found in the tutorial.

Initialization

import motor
from beanie import init_beanie


async def init():
    # Crete Motor client
    client = motor.motor_asyncio.AsyncIOMotorClient(
        "mongodb://user:pass@host:27017"
    )

    # Init beanie with the Note document class
    await init_beanie(database=client.db_name, document_models=[Product])

Create

chocolate = Category(name="Chocolate")

# Single:

bar = Product(name="Tony's", price=5.95, category=chocolate)
await bar.insert()

# Many

milka = Product(name="Milka", price=3.05, category=chocolate)
peanut_bar = Product(name="Peanut Bar", price=4.44, category=chocolate)
await Product.insert_many([milka, peanut_bar])

Other details and examples could be found in the tutorial

Find

# Single

# By id
bar = await Product.get("608da169eb9e17281f0ab2ff")

# By name
bar = await Product.find_one(Product.name == "Peanut Bar")

# Many

# By category

chocolates = await Product.find(
    Product.category.name == "Chocolate"
).to_list()

# And by price

chocolates = await Product.find(
    Product.category.name == "Chocolate",
    Product.price < 5
).to_list()

# OR

chocolates = await Product.find(
    Product.category.name == "Chocolate").find(
    Product.price < 5).to_list()

# Complex example:

class ProductShortView(BaseModel):
    name: str
    price: float


products = await Product.find(
    Product.category.name == "Chocolate",
    Product.price < 3.5
).sort(-Product.price).limit(10).project(ProductShortView)

# All

all_products = await Product.all().to_list()

Information about sorting, skips, limits, and projections could be found in the tutorial

Update

# Single 
await Product.find_one(Product.name == "Milka").set({Product.price: 3.33})

# Or
bar = await Product.find_one(Product.name == "Milka")
await bar.update(Set({Product.price: 3.33}))

# Or
bar.price = 3.33
await bar.replace()

# Many
await Product.find(
    Product.category.name == "Chocolate"
).inc({Product.price: 1})

More details and examples about update queries could be found in the tutorial

Delete

# Single 
await Product.find_one(Product.name == "Milka").delete()

# Or
bar = await Product.find_one(Product.name == "Milka")
await bar.delete()

# Many
await Product.find(
    Product.category.name == "Chocolate"
).delete()

More information could be found in the tutorial

Aggregate

# With preset methods

avg_price = await Product.find(
    Product.category.name == "Chocolate"
).avg(Product.price)

# Or without find query

avg_price = await Product.avg(Product.price)

# Native syntax 

class OutputItem(BaseModel):
    id: str = Field(None, alias="_id")
    total: int
    
result = await Product.find(
    Product.category.name == "Chocolate").aggregate(
    [{"$group": {"_id": "$category.name", "total": {"$avg": "$price"}}}],
    projection_model=OutputItem
).to_list()

Information about aggregation preset aggregation methods and native syntax aggregations could be found in the tutorial

Documentation

  • Tutorial - Usage examples with descriptions
  • API - Full list of the classes and methods

Example Projects

  • FastAPI Demo - Beanie and FastAPI collaboration demonstration. CRUD and Aggregation.
  • Indexes Demo - Regular and Geo Indexes usage example wrapped to a microservice.

Articles

Resources

  • GitHub - GitHub page of the project
  • Changelog - list of all the valuable changes
  • Discord - ask your questions, share ideas or just say Hello!!

Supported by JetBrains

JetBrains

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

beanie-1.0.0.tar.gz (28.7 kB view details)

Uploaded Source

Built Distribution

beanie-1.0.0-py3-none-any.whl (43.8 kB view details)

Uploaded Python 3

File details

Details for the file beanie-1.0.0.tar.gz.

File metadata

  • Download URL: beanie-1.0.0.tar.gz
  • Upload date:
  • Size: 28.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.8.5 Linux/5.8.0-48-generic

File hashes

Hashes for beanie-1.0.0.tar.gz
Algorithm Hash digest
SHA256 96ca029f1a01c72783b7eaf36d407b0769800a5bc2fe1deb65ea411806f2bf28
MD5 095496c54f5aed02ba7c430e86dcedab
BLAKE2b-256 8592d7eaa26079467d24a60e49ea83804b0e15cee36b2702d77efaf951033124

See more details on using hashes here.

File details

Details for the file beanie-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: beanie-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 43.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.4 CPython/3.8.5 Linux/5.8.0-48-generic

File hashes

Hashes for beanie-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dff8842d6f96ca89a58a3ae1d55b0a8e2e023e9048031f2e43a91aa3979c11de
MD5 bf55aec4c09448865a10180608446203
BLAKE2b-256 3a19cabf653aa583bd5b95315c3dd500ff6c715293b25664fd77f2d85af3c2ac

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page