0
0
FastAPIframework~10 mins

MongoDB integration with Motor in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an async MongoDB client using Motor.

FastAPI
from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient([1])
db = client.test_database
Drag options to blanks, or click blank then click option'
A'http://localhost:27017'
B'mongodb://localhost:27017'
C'ftp://localhost:27017'
D'localhost:27017'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'http://' or 'ftp://' instead of 'mongodb://'.
Omitting the protocol prefix.
2fill in blank
medium

Complete the FastAPI endpoint to insert a document into MongoDB asynchronously.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.post('/add')
async def add_item(item: dict):
    result = await db.items.[1](item)
    return {'inserted_id': str(result.inserted_id)}
Drag options to blanks, or click blank then click option'
Ainsert_one
Bfind_one
Cdelete_one
Dupdate_one
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'find_one' which only retrieves data.
Using 'delete_one' or 'update_one' which modify or remove data.
3fill in blank
hard

Fix the error in the async function to find one document by name.

FastAPI
async def get_item(name: str):
    document = await db.items.find_one({{'name': [1])
    return document
Drag options to blanks, or click blank then click option'
Astr(name)
B'name'
Cname()
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around the variable name, making it a string literal.
Calling the variable as a function.
4fill in blank
hard

Fill both blanks to update a document's field asynchronously.

FastAPI
async def update_item(name: str, new_value: str):
    result = await db.items.update_one(
        {{'name': [1],
        {{'$set': {{'field': [2]
    )
    return result.modified_count
Drag options to blanks, or click blank then click option'
Aname
Bnew_value
C'new_value'
D'name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using string literals instead of variables.
Mixing up which variable goes where.
5fill in blank
hard

Fill all three blanks to delete a document by id asynchronously.

FastAPI
from bson import ObjectId

async def delete_item(item_id: str):
    result = await db.items.delete_one({{'_id': [1]([2])}})
    return result.deleted_count

# Call example: await delete_item([3])
Drag options to blanks, or click blank then click option'
AObjectId
Bitem_id
C'some_id_string'
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the id as a plain string without ObjectId conversion.
Using wrong variable names in the call example.