Flask-PyMongo is a Python library that provides PyMongo support for Flask applications. It acts as a bridge between Flask and PyMongo, wrapping PyMongo's MongoClient, Database, and Collection classes to offer convenience helpers and seamless integration with Flask's configuration system. The current version, 3.0.1, is actively maintained and generally follows the release cycles of Flask and PyMongo.
pip install Flask-PyMongoVerified import paths — ran on the pinned version, not inferred.
This quickstart initializes a Flask application and connects it to a MongoDB instance using Flask-PyMongo. The MongoDB URI is configured via `app.config['MONGO_URI']`, which can be set through an environment variable. A simple route demonstrates checking the database connection.
Migrate your application's MongoDB configuration to use the `MONGO_URI` format (e.g., `mongodb://localhost:27017/myDatabase`). Pin `Flask-PyMongo<2.0` if immediate migration is not possible.
Ensure your project's Flask version is 3.0 or higher, PyMongo is 4.0 or higher, and Python is 3.9 or higher. Adjust your `requirements.txt` accordingly.
If you require PyMongo to connect immediately upon instantiation, initialize it with `mongo = PyMongo(app, connect=True)`. Otherwise, be aware that the actual connection might be delayed until the first database operation.
Always include a database name in your `MONGO_URI` (e.g., `mongodb://localhost:27017/myDatabase`) if you intend to use `mongo.db` directly. Alternatively, access collections via `mongo.cx.<database_name>.<collection_name>`.
Ensure you have installed `Flask-PyMongo` within your active Python environment. Use `pip install Flask-PyMongo` (or `pip3 install Flask-PyMongo`) and verify with `python -c 'import flask_pymongo'` in the same environment.
Verify that your MongoDB server is running and accessible from where your Flask application is hosted. Check the `MONGO_URI` for correct host, port, and credentials. Ensure no firewall is blocking the connection. Restarting the MongoDB service often resolves this.
Double-check your MongoDB username, password, and database name in the `MONGO_URI`. Ensure the user has the necessary permissions. For older MongoDB versions, explicitly include the database name in the URI even if authenticating against `admin`.