0Pricing
FastAPI Backend Development Bootcamp · 강의

Motor를 활용한 비동기 MongoDB 접근

Motor 비동기 드라이버로 FastAPI를 MongoDB에 연결하고 앱 수명 주기에서 연결 수명을 관리합니다.

Motor를 활용한 비동기 MongoDB 접근은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Motor for Async MongoDB

FastAPI is an async framework. If you talk to MongoDB with a blocking driver like pymongo, every database call freezes the event loop and kills concurrency.

Motor is MongoDB's official async driver. It wraps PyMongo and exposes coroutine-based methods you can await, so the event loop stays free to handle other requests while a query is in flight.

  • motor.motor_asyncio.AsyncIOMotorClient — the async client.
  • Every I/O call (find_one, insert_one, ...) returns an awaitable.
  • Higher-level ODMs like Beanie are built on top of Motor.

Installing the Driver

Install Motor and its peer dependency. Motor pulls in a compatible PyMongo automatically.

  • motor — async driver.
  • fastapi and uvicorn — the web layer.

For Beanie integration later you would also add beanie, but Motor alone is enough to read and write documents directly.

pip install motor fastapi uvicorn
# motor brings in a compatible pymongo wheel
# verify the install
python -c "import motor; print(motor.version)"

Creating an Async Client

You create a single AsyncIOMotorClient for the whole application. The client manages an internal connection pool, so you should never create a new client per request.

Indexing into the client gives you a database, and indexing into that gives you a collection. None of this opens a socket yet — connections are established lazily on the first real operation.

from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient("mongodb://localhost:27017")
database = client["shop"]
products = database["products"]

# Equivalent attribute-style access
# database = client.shop
# products = database.products

Awaiting Your First Query

Because every Motor I/O method is a coroutine, you must await it inside an async function. Forgetting await returns an unresolved coroutine object, not your data.

insert_one returns an InsertOneResult whose inserted_id is the generated ObjectId. find_one returns the matching document as a plain dict, or None.

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient

async def main():
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    products = client["shop"]["products"]

    result = await products.insert_one({"name": "Keyboard", "price": 49})
    print("inserted id:", result.inserted_id)

    doc = await products.find_one({"name": "Keyboard"})
    print(doc)

asyncio.run(main())

The Connection Lifecycle Problem

Where should the client live? Options that look tempting but are wrong:

  • A new client inside each route — exhausts connections and is slow.
  • A module-level client created at import time — connects before the app is ready and is hard to close cleanly.

The right place is the app's lifespan: open the client when the server starts, store it, and close it when the server shuts down. This guarantees one pooled client per process and a clean teardown.

The Lifespan Context Manager

Modern FastAPI uses an async context manager passed as lifespan. Code before yield runs on startup; code after yield runs on shutdown.

Store shared resources on app.state so any route can reach them. Calling client.close() on shutdown returns pooled sockets to the OS gracefully.

from contextlib import asynccontextmanager
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.mongo = AsyncIOMotorClient("mongodb://localhost:27017")
    app.state.db = app.state.mongo["shop"]
    yield
    app.state.mongo.close()

app = FastAPI(lifespan=lifespan)

Verifying the Connection on Startup

The client connects lazily, so a wrong host won't fail until the first query. To fail fast at boot, send a lightweight ping command during startup.

If the ping raises, the server crashes immediately with a clear error instead of silently serving 500s later.

from contextlib import asynccontextmanager
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient

@asynccontextmanager
async def lifespan(app: FastAPI):
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    await client.admin.command("ping")  # raises if unreachable
    app.state.db = client["shop"]
    app.state.mongo = client
    yield
    client.close()

app = FastAPI(lifespan=lifespan)

Injecting the Database into Routes

Reaching into request.app.state directly works but couples routes to global state. A cleaner pattern is a small dependency that returns the database handle.

This keeps routes testable — in tests you can override the dependency to point at a throwaway database.

from fastapi import Depends, Request
from motor.motor_asyncio import AsyncIOMotorDatabase

def get_db(request: Request) -> AsyncIOMotorDatabase:
    return request.app.state.db

@app.get("/products/{name}")
async def get_product(name: str, db: AsyncIOMotorDatabase = Depends(get_db)):
    doc = await db["products"].find_one({"name": name})
    return doc or {"error": "not found"}

Serializing the ObjectId

MongoDB documents carry an _id field of type ObjectId, which is not JSON serializable. Returning a raw document from a route triggers a serialization error.

Convert _id to a string before returning, or map it into a Pydantic model. A simple helper keeps your routes clean.

def serialize(doc: dict) -> dict:
    if doc and "_id" in doc:
        doc["id"] = str(doc["_id"])
        del doc["_id"]
    return doc

# Usage inside a route:
# raw = await db["products"].find_one({"name": name})
# return serialize(raw)

print(serialize({"_id": "507f1f77bcf86cd799439011", "name": "Mouse"}))

Iterating Cursors Asynchronously

find() returns an async cursor, not a list. You consume it with async for, or materialize it with to_list().

  • await cursor.to_list(length=100) — load up to 100 docs at once.
  • async for doc in cursor: — stream documents one at a time, ideal for large result sets.
from fastapi import Depends
from motor.motor_asyncio import AsyncIOMotorDatabase

@app.get("/products")
async def list_products(db: AsyncIOMotorDatabase = Depends(get_db)):
    cursor = db["products"].find({"price": {"$lt": 100}})
    return await cursor.to_list(length=50)

# Streaming alternative:
# async for doc in cursor:
#     process(doc)

Configuring the Pool and Timeouts

The client constructor accepts tuning options. Read them from environment variables so the same code works across dev and production.

  • maxPoolSize — cap on concurrent connections.
  • serverSelectionTimeoutMS — how long to wait before declaring the server unreachable.

Loading the URI from the environment also keeps credentials out of source control.

import os
from motor.motor_asyncio import AsyncIOMotorClient

def make_client() -> AsyncIOMotorClient:
    uri = os.environ.get("MONGODB_URI", "mongodb://localhost:27017")
    return AsyncIOMotorClient(
        uri,
        maxPoolSize=20,
        serverSelectionTimeoutMS=5000,
    )

Quick Check

Where should the AsyncIOMotorClient be created and destroyed in a FastAPI app?

Recap

You connected FastAPI to MongoDB with the async Motor driver:

  • Motor exposes awaitable methods so MongoDB I/O never blocks the event loop.
  • Create one AsyncIOMotorClient per process — it owns a connection pool.
  • Open and close the client in the lifespan context manager, and ping on startup to fail fast.
  • Expose the database through a Depends dependency for clean, testable routes.
  • Convert _id (an ObjectId) to a string before returning JSON.
  • Consume find() cursors with to_list() or async for, and tune maxPoolSize and timeouts from environment variables.

This Motor foundation is exactly what Beanie builds on next.

자주 묻는 질문

“Motor를 활용한 비동기 MongoDB 접근” 강의는 무료인가요?

네 — “Motor를 활용한 비동기 MongoDB 접근” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“Motor를 활용한 비동기 MongoDB 접근”에서 뭘 배우나요?

Motor 비동기 드라이버로 FastAPI를 MongoDB에 연결하고 앱 수명 주기에서 연결 수명을 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Motor를 활용한 비동기 MongoDB 접근” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Motor를 활용한 비동기 MongoDB 접근
  2. Beanie ODM을 활용한 문서 모델링
  3. 집계 파이프라인과 복잡한 쿼리
  4. 스키마 진화와 문서 마이그레이션
← FastAPI Backend Development Bootcamp(으)로 돌아가기