Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃摑 Add MongoDB recipe to docs #11439

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
99 changes: 99 additions & 0 deletions docs/en/docs/how-to/async-mongodb-motor-beanie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Async MongoDB with Motor

**FastAPI** can also be integrated with any <abbr title="Distributed database (Big Data), also 'Not Only SQL'">NoSQL</abbr>.

This includes, but is not limited to:

* **Cassandra**
* **CouchDB**
* **ArangoDB**
* **ElasticSearch**
* etc

[Motor](https://motor.readthedocs.io/en/stable/index.html) is an asynchronous Python driver for MongoDB.

## Install Motor

```bash
pip install motor
```

## Create a MongoDB Client

```Python hl_lines="10"
from motor.motor_asyncio import AsyncIOMotorClient

class Database:
client: AsyncIOMotorClient = None

db = Database()

@app.on_event("startup")
async def startup_db_client():
db.client = AsyncIOMotorClient("mongodb://localhost:27017")

@app.on_event("shutdown")
async def shutdown_db_client():
db.client.close()
```

## Interact with MongoDB

```Python hl_lines="7-8"
from fastapi import FastAPI

app = FastAPI()

@app.post("/items/")
async def create_item(item: dict) -> str:
collection = db.client.mydatabase.items
result = await collection.insert_one(item)
return {"id": str(result.inserted_id)}
```

## Integrate Beanie ODM

[Beanie](https://roman-right.github.io/beanie/) is an async Python object-document mapper (ODM) built on top of Motor and Pydantic.
You can extend the Motor example above by defining `Document` models and adding an initialization call to DB startup.

```Python
from beanie import Document

class Item(Document):
name: str
description: str
tax: float
```

Initialize Beanie with Motor client:

```Python hl_lines="8-11"
from beanie import init_beanie

# ...

@app.on_event("startup")
async def startup_db_client():
db.client = AsyncIOMotorClient("mongodb://localhost:27017")
await init_beanie(
database=db.client.mydatabase, # Use your database name
document_models=[Item]
)
```

## Use Beanie Mapped Object

Since `Item` is also a Pydantic model, it can be integrated into FastAPI's [response model](https://fastapi.tiangolo.com/tutorial/response-model/).

```Python
@app.get(
"/items/{item_id}",
response_model=Item,
response_model_exclude={"tax"}
)
async def get_item(item_id: str) -> Item:
item = await Item.find_one({"_id": item_id})
if item is not None:
return item
raise HTTPException(status_code=404, detail="Item not found")
```
1 change: 1 addition & 0 deletions docs/en/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ nav:
- how-to/separate-openapi-schemas.md
- how-to/custom-docs-ui-assets.md
- how-to/configure-swagger-ui.md
- how-to/async-mongodb-motor-beanie.md
- how-to/sql-databases-peewee.md
- how-to/async-sql-encode-databases.md
- how-to/nosql-databases-couchbase.md
Expand Down