MongoDB with FastAPI & Python

Lesson 4 of 6

Basic CRUD with Motor

Motor's methods mirror MongoDB's query language closely, and every call is async.

# Create
result = await tasks_collection.insert_one({"title": "Buy groceries", "done": False})
new_id = result.inserted_id

# Read one
task = await tasks_collection.find_one({"_id": new_id})

# Read many
cursor = tasks_collection.find({"done": False})
incomplete_tasks = await cursor.to_list(length=100)

# Update
await tasks_collection.update_one({"_id": new_id}, {"$set": {"done": True}})

# Delete
await tasks_collection.delete_one({"_id": new_id})

Reading the pieces

  • The first argument to each method is a filter, a document describing which record(s) to match, {} matches everything.
  • find() returns a cursor, not the data itself, you iterate it (or call .to_list()) to actually fetch documents.
  • update_one needs an update operator like $set, MongoDB won't just replace the whole document unless you ask it to.

📝 CRUD Quiz

Passing score: 70%
  1. 1.What does tasks_collection.find({...}) return?

  2. 2.To update specific fields on a document without replacing the whole thing, you use the ____ operator.

  3. 3.Every Motor method call must be awaited.