Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 72 ยท Databases

Flask with MongoDB (PyMongo)

Use MongoDB from Flask with PyMongo. Connect, insert and query documents, handle ObjectId in URLs and JSON, update and delete safely, add indexes, and test with mongomock.

So far this course stored data in tables. MongoDB is a document database: instead of rows in fixed-shape tables, it stores JSON-like documents in collections, and different documents in one collection may have different fields. That fits data that is naturally nested or that changes shape often (product catalogs, event logs, content with variable attributes). It is not "better" than SQL; it is different. If your data has many relationships and you need joins and strict constraints, a relational database (Flask-SQLAlchemy) is usually the better fit.

Flask has no official MongoDB layer. The recommended approach is to use the official driver, PyMongo, directly. This lesson shows the pattern and the things that trip people up: ObjectId, JSON serialization, and untrusted query input.

How the code runs here

PyMongo needs a MongoDB server to talk to, and the browser cannot run one. The editors below use mongomock, a pure-Python in-memory library that implements the PyMongo interface, so the calls you read are the same ones you would write for the real driver. The only line that differs is where the client comes from:

Python
# real project (needs a running MongoDB and: pip install pymongo)
from pymongo import MongoClient
client = MongoClient(os.environ["MONGO_URI"])       # e.g. mongodb://localhost:27017
db = client["shop"]

# in these lessons (no server)
import mongomock
client = mongomock.MongoClient()
db = client["shop"]

Everything after that line is identical. MongoClient is thread-safe and manages its own connection pool, so create one per process and share it; do not open a client per request. Keep the connection string in configuration (Configuration); Atlas URIs contain a password.

Documents and CRUD

A collection is created the first time you use it. Every document gets a unique _id, an ObjectId by default, assigned when you insert.

Python Insert, find, update and delete documents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Points worth remembering:

  • Filters use operators that start with $: $lt, $gt, $in, $ne, $and, $or. Dotted paths reach nested fields ("stock.berlin").
  • Always update with operators ($set, $inc, $push). replace_one or an update without an operator overwrites the whole document.
  • find returns a lazy cursor; wrap it in list() or loop over it. Add .limit() and .skip() (or better, range queries on an indexed field) for pagination.
  • count_documents takes a filter; the older count() is gone.

ObjectId in URLs and JSON

ObjectId is not a string. Two practical problems follow:

  1. A URL gives you a string, but a query for {"_id": "65f1..."} will not match an ObjectId. Convert with ObjectId(text), and handle invalid text (bson.errors.InvalidId) as a 404.
  2. Flask's jsonify cannot serialize ObjectId and raises TypeError. Convert _id to a string before returning, or teach Flask how.

A tidy way is a converter that does both jobs for URLs plus a JSON provider that renders ids as strings.

Python A JSON API over MongoDB

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The extra is_admin and role fields never reach the database because of the allowlist. MongoDB does not validate shapes for you, so a handler that stores request.get_json() directly lets clients write any field. Add checks like the title test, or use a validation library (Validation and Serialization).

Query injection

SQL injection has a MongoDB cousin: operator injection. If you pass user input straight into a filter, a JSON body like {"password": {"$ne": null}} becomes a query that matches any password.

Python
# dangerous: the client controls the shape of the filter
user = users.find_one({"email": data["email"], "password": data["password"]})

Defend by checking that values are the types you expect (isinstance(value, str)), by building filters from known keys, and by never storing plain passwords in the first place (Password Hashing): look the user up by email, then verify the hash in Python.

Indexes and design

Without an index, MongoDB scans every document. Create indexes for the fields you filter and sort by; a unique index also enforces uniqueness, because inserting a duplicate raises DuplicateKeyError:

Python
products.create_index("name")
users.create_index("email", unique=True)

A few design habits help:

  • Embed data that is always read together (an order with its line items) and reference data shared widely (store a customer_id). There are no joins like SQL's; $lookup exists but is for occasional use.
  • Documents are limited to 16 MB, so do not grow an unbounded array inside one document.
  • Multi-document transactions exist in replica sets but are heavier than in SQL; design so that one document update is atomic.
  • Use a managed service (MongoDB Atlas) in production, with authentication, TLS and an IP allowlist. A MongoDB reachable from the internet without auth is a classic data leak.

Testing

Use mongomock in tests exactly as above (inject the database through the application factory), or a throwaway real MongoDB in a container for behavior that mock libraries do not reproduce, such as some aggregation stages and index behavior. Testing Flask Apps shows the fixture style.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does find_one({'_id': '65f1...'}) with a plain string usually find nothing?

    An ObjectId is a distinct type. The 24-character text from the URL has to be converted before it can match.
  2. 2. Which update keeps other fields of the document intact?

    $set changes only the named fields. replace_one swaps in an entirely new document.
  3. 3. What is operator injection?

    If request data is placed into a filter unchecked, clients can smuggle in $ operators. Validate types and build filters from known keys.
  4. 4. How should a Flask app hold its MongoClient?

    MongoClient is thread-safe and pools connections. Creating one per request wastes connections and time.

Summary

  • MongoDB stores JSON-like documents in collections; PyMongo is the driver, and a single shared MongoClient is created per process.
  • CRUD uses insert_one/many, find/find_one with operator filters, update_one/many with $set/$inc/$push, and delete_one/many.
  • Convert URL ids with ObjectId(...) (404 on InvalidId) and serialize ids as strings in JSON.
  • Allowlist the fields you store and validate types to prevent mass assignment and operator injection.
  • Index what you filter and sort on; embed what you read together; secure the server.
  • The runnable examples use mongomock, which mirrors PyMongo's interface without a server.

Next: connect Flask to server databases in Flask with PostgreSQL and MySQL.