Speed up the slow orders query
Coding · Python · 7.2 min
2done well1gap
Details1 gap · Code · 6 lines
Review
Moved the filter into the query and projected only the needed fields. Did not add the index the sort needs.
Done well
- Filters in the database, not in Python
- Returns only the fields the page shows
Gaps
- No index on customer_id + created_at, so the sort still scans
Handed in
def recent_orders(db, customer_id):
# was: load every order, filter in Python
return db.orders.find(
{"customer_id": customer_id},
{"_id": 1, "total": 1, "created_at": 1},
).sort("created_at", -1).limit(20)