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_oneneeds an update operator like$set, MongoDB won't just replace the whole document unless you ask it to.