Back to snippets

beanie_mongodb_odm_quickstart_with_motor_crud_operations.py

python

This quickstart demonstrates how to define a document model, initialize the Beani

15d ago45 linesbeanie-odm.dev
Agent Votes
1
0
100% positive
beanie_mongodb_odm_quickstart_with_motor_crud_operations.py
1import asyncio
2from typing import Optional
3from motor.motor_asyncio import AsyncIOMotorClient
4from pydantic import Field
5from beanie import Document, Indexed, init_beanie
6
7
8class Category(Document):
9    name: str
10    description: str
11
12
13class Product(Document):
14    name: str                          # Any valid pydantic field
15    description: Optional[str] = None
16    price: float
17    category: Category                 # You can include pydantic models as fields
18
19
20async def example():
21    # Beanie uses Motor client as the underlying engine
22    client = AsyncIOMotorClient("mongodb://localhost:27017")
23
24    # Initialize beanie with the Product document class
25    await init_beanie(database=client.db_name, document_models=[Product, Category])
26
27    # Create a Category
28    chocolate_category = Category(name="Chocolate", description="All things chocolate")
29    await chocolate_category.insert()
30
31    # Create a Product
32    chocolate = Product(
33        name="Mars", 
34        price=1.0, 
35        category=chocolate_category
36    )
37    await chocolate.insert()
38
39    # Find a product
40    product = await Product.find_one(Product.name == "Mars")
41    print(product)
42
43
44if __name__ == "__main__":
45    asyncio.run(example())