Skip to content

How to Fix Python Motor Async MongoDB Error

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Python Motor Async MongoDB Error. We cover key concepts, practical examples, and best practices.

Motor raises ConnectionFailure, ServerSelectionTimeoutError, or CursorNotFound when the MongoDB server is unreachable, the connection string is wrong, or the cursor exceeds its timeout.

The Wrong Way

from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.test_db
cursor = db.users.find({"name": "Alice"})
result = cursor.next()
print(result)

Output:

TypeError: 'AsyncIOMotorCursor' object is not an iterator

The Right Way

from motor.motor_asyncio import AsyncIOMotorClient
import asyncio

async def main():
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    db = client.test_db
    cursor = db.users.find({"name": "Alice"})
    async for doc in cursor:
        print(doc)

asyncio.run(main())

Output:

{'_id': ObjectId('...'), 'name': 'Alice', 'email': 'alice@example.com'}

Prevention Tips

  • Use async for to iterate Motor cursors, not next().
  • Set serverSelectionTimeoutMS for faster failure detection.
  • Use await cursor.to_list(length) to get results as a list.
  • Close the client with client.close() on shutdown.
  • Handle ConnectionFailure and ServerSelectionTimeoutError.

Common Mistakes with motor async

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between Motor and PyMongo?

Motor is an async MongoDB driver built on PyMongo. PyMongo is synchronous. Motor uses async/await and async for for non-blocking database operations.

Why does Motor raise ServerSelectionTimeoutError?

The client cannot connect to any MongoDB server within the timeout. Check that MongoDB is running, the connection string is correct, and network connectivity exists between the client and server.

How do I use Motor with FastAPI?

Create the Motor client as a module-level variable. Initialize it in a startup event. Use Depends() to inject the database into route handlers. Close the client in a shutdown event.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro