Bird
Raised Fist0
FastAPIframework~20 mins

MongoDB integration with Motor in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
MongoDB Motor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Find documents with a specific field value
Given a Motor collection with documents containing a field status, what will be the output of this query?

cursor = collection.find({"status": "active"})
results = await cursor.to_list(length=100)


Assume the collection has 3 documents with status set to "active".
FastAPI
cursor = collection.find({"status": "active"})
results = await cursor.to_list(length=100)
AAn empty list because <code>to_list</code> requires a callback
BA list of all documents in the collection regardless of <code>status</code>
CA list of 3 documents where each document has <code>status</code> equal to <code>"active"</code>
DA single document with <code>status</code> equal to <code>"active"</code>
Attempts:
2 left
💡 Hint
Remember that find returns a cursor for all matching documents, and to_list collects them into a list.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in Motor query
Which option contains a syntax error when trying to update a document using Motor in FastAPI?

Code snippet:
await collection.update_one({"_id": id}, {"$set": {"name": "Alice"}})
Aawait collection.update_one({"_id": id}, {"$set": {"name": "Alice"}})
Bawait collection.update_one({"_id": id}, {"$set": {"name": "Alice"}});
Cawait collection.update_one({"_id": id}, {"$set": {"name": "Alice"}}
Dawait collection.update_one({"_id": id}, {"$set": {"name": "Alice"}}))
Attempts:
2 left
💡 Hint
Check for unmatched parentheses or extra characters.
optimization
advanced
2:30remaining
Optimize fetching large data sets with Motor
You want to fetch 10,000 documents from a Motor collection efficiently. Which approach is best to avoid high memory usage?
AUse <code>async for doc in collection.find():</code> to process documents one by one.
BUse <code>await collection.find().to_list(length=10000)</code> to get all documents at once.
CUse <code>await collection.find_one()</code> in a loop 10,000 times.
DUse <code>collection.find().limit(10000)</code> without awaiting.
Attempts:
2 left
💡 Hint
Think about memory usage when loading many documents.
🔧 Debug
advanced
1:30remaining
Debug missing await in Motor query
What error will occur if you forget to use await when calling collection.find_one() in an async FastAPI route?
FastAPI
result = collection.find_one({"_id": id})
ASyntaxError: missing await keyword
BTypeError: object coroutine can't be used directly
CRuntimeError: event loop is closed
DNo error, result contains the document
Attempts:
2 left
💡 Hint
Remember that Motor methods return coroutines that must be awaited.
🧠 Conceptual
expert
3:00remaining
Understanding Motor client connection lifecycle
In a FastAPI app using Motor, what is the best practice to manage the MongoDB client connection to avoid creating multiple clients on each request?
ACreate a single Motor client instance at app startup and reuse it for all requests.
BCreate a Motor client inside a dependency with <code>yield</code> and close it after each request.
CCreate a Motor client globally but close it after each request.
DCreate a new Motor client inside each route handler function.
Attempts:
2 left
💡 Hint
Think about connection overhead and resource management.

Practice

(1/5)
1. What is the main benefit of using Motor with FastAPI for MongoDB operations?
easy
A. It automatically converts ObjectId to string.
B. It provides a graphical interface for MongoDB.
C. It allows asynchronous, non-blocking database calls.
D. It replaces the need for FastAPI routing.

Solution

  1. Step 1: Understand Motor's role in FastAPI

    Motor is an async driver for MongoDB, enabling non-blocking calls in FastAPI apps.
  2. Step 2: Identify the main benefit

    Non-blocking calls keep the app responsive and fast by not waiting for DB operations.
  3. Final Answer:

    It allows asynchronous, non-blocking database calls. -> Option C
  4. Quick Check:

    Motor = async, non-blocking calls [OK]
Hint: Motor means async MongoDB calls in FastAPI [OK]
Common Mistakes:
  • Thinking Motor provides UI tools
  • Assuming Motor auto-converts ObjectId
  • Confusing Motor with FastAPI routing
2. Which of the following is the correct way to define a Motor client in FastAPI?
easy
A. client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
B. client = MotorClient('mongodb://localhost:27017')
C. client = AsyncMongoClient('localhost:27017')
D. client = motor.MongoClient('mongodb://localhost:27017')

Solution

  1. Step 1: Recall Motor client syntax

    The Motor async client is created using motor.motor_asyncio.AsyncIOMotorClient with the MongoDB URI.
  2. Step 2: Check each option

    Only client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') uses the correct class and URI format for Motor.
  3. Final Answer:

    client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') -> Option A
  4. Quick Check:

    Motor client = AsyncIOMotorClient [OK]
Hint: Use AsyncIOMotorClient from motor.motor_asyncio [OK]
Common Mistakes:
  • Using MotorClient instead of AsyncIOMotorClient
  • Omitting 'motor.motor_asyncio' prefix
  • Using synchronous MongoClient
3. Given this FastAPI async function using Motor, what will be the output?
async def get_user(db, user_id):
    user = await db.users.find_one({"_id": user_id})
    return str(user["_id"])
medium
A. Returns None if user_id is not found.
B. Returns the string representation of the user's ObjectId.
C. Raises a TypeError because ObjectId can't be converted to string.
D. Returns the user document as a dictionary.

Solution

  1. Step 1: Analyze the async function

    The function awaits a find_one query by _id and then converts the _id field to string.
  2. Step 2: Understand the output

    It returns the string form of the ObjectId, not the whole document or None.
  3. Final Answer:

    Returns the string representation of the user's ObjectId. -> Option B
  4. Quick Check:

    str(ObjectId) = string id [OK]
Hint: str() converts ObjectId to string safely [OK]
Common Mistakes:
  • Expecting full user dict as output
  • Thinking ObjectId can't be stringified
  • Assuming None is returned if not found
4. Identify the error in this Motor usage inside FastAPI:
async def fetch_items(db):
    items = db.items.find()
    return await items.to_list(length=100)
medium
A. Missing await before db.items.find() call.
B. to_list() should not be awaited.
C. find() returns a cursor and must be awaited before to_list().
D. No error; code is correct.

Solution

  1. Step 1: Understand Motor's find() behavior

    Motor's find() returns an async cursor immediately; no await needed here.
  2. Step 2: Check to_list() usage

    to_list() is a coroutine and must be awaited to get the list of documents.
  3. Final Answer:

    No error; code is correct. -> Option D
  4. Quick Check:

    find() no await, to_list() await [OK]
Hint: Await to_list(), not find() [OK]
Common Mistakes:
  • Awaiting find() call incorrectly
  • Not awaiting to_list() causing runtime error
  • Confusing synchronous and async cursor methods
5. You want to return a list of users from MongoDB in FastAPI, but each user's _id must be a string, not ObjectId. Which code snippet correctly does this?
hard
A. users = await db.users.find().to_list(100) return [{**u, '_id': str(u['_id'])} for u in users]
B. users = await db.users.find().to_list(100) return [u for u in users if str(u['_id'])]
C. users = await db.users.find().to_list(100) return [str(u) for u in users]
D. users = await db.users.find().to_list(100) return [u['_id'] for u in users]

Solution

  1. Step 1: Fetch users as list of dicts

    await db.users.find().to_list(100) returns list of user dicts with ObjectId _id fields.
  2. Step 2: Convert each user's _id to string

    Use list comprehension to copy each dict and replace _id with str(u['_id']).
  3. Final Answer:

    users = await db.users.find().to_list(100) return [{**u, '_id': str(u['_id'])} for u in users] -> Option A
  4. Quick Check:

    Convert ObjectId to string per user [OK]
Hint: Use dict unpacking and str() on _id in list comprehension [OK]
Common Mistakes:
  • Returning ObjectId directly without conversion
  • Trying to convert whole user dict to string
  • Filtering users instead of converting _id