{"id":8173,"library":"flask-pymongo","title":"Flask-PyMongo","description":"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.","status":"active","version":"3.0.1","language":"en","source_language":"en","source_url":"https://github.com/mongodb-labs/flask-pymongo","tags":["flask","mongodb","pymongo","database","web-framework","extension"],"install":[{"cmd":"pip install Flask-PyMongo","lang":"bash","label":"Install Flask-PyMongo"}],"dependencies":[{"reason":"Web framework integration","package":"Flask","optional":false},{"reason":"MongoDB driver","package":"PyMongo","optional":false}],"imports":[{"note":"The `flask.ext` import path was deprecated and removed in Flask-PyMongo 2.0. Use direct import from `flask_pymongo`.","wrong":"from flask.ext.pymongo import PyMongo","symbol":"PyMongo","correct":"from flask_pymongo import PyMongo"}],"quickstart":{"code":"from flask import Flask, jsonify\nfrom flask_pymongo import PyMongo\nimport os\n\napp = Flask(__name__)\n\n# Configure MongoDB URI from environment variable or default\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\", \"mongodb://localhost:27017/myDatabase\")\n\nmongo = PyMongo(app)\n\n@app.route(\"/\")\ndef home_page():\n    try:\n        # Ensure connection is established before querying\n        mongo.cx.admin.command('ping')\n        return jsonify(message=\"MongoDB connection successful!\")\n    except Exception as e:\n        return jsonify(message=f\"MongoDB connection failed: {e}\"), 500\n\nif __name__ == \"__main__\":\n    # In a real application, you might use a more robust run method or WSGI server\n    app.run(debug=True)","lang":"python","description":"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."},"warnings":[{"fix":"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.","message":"Flask-PyMongo 2.0 introduced breaking changes, most notably deprecating individual configuration variables (e.g., `MONGO_HOST`, `MONGO_PORT`, `MONGO_DBNAME`) in favor of a single `MONGO_URI`.","severity":"breaking","affected_versions":"<2.0 to >=2.0"},{"fix":"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.","message":"Version 3.x of Flask-PyMongo requires Flask 3.0+ and PyMongo 4.0+ and Python 3.9+. Older versions of Flask or PyMongo are not supported.","severity":"breaking","affected_versions":"All versions"},{"fix":"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.","message":"By default, Flask-PyMongo sets `connect=False` during initialization to prevent PyMongo from connecting immediately, which avoids fork-safety issues. If you need immediate connection, explicitly pass `connect=True`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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>`.","message":"As of Flask-PyMongo 2.2, if the `MONGO_URI` does not specify a database name, the `mongo.db` attribute will be `None`. Attempting to access `mongo.db.<collection>` will result in an AttributeError.","severity":"gotcha","affected_versions":">=2.2"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"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.","cause":"Flask-PyMongo is either not installed or installed in a different Python environment (e.g., for Python 2 while running Python 3, or in an inactive virtual environment).","error":"ModuleNotFoundError: No module named 'flask_pymongo'"},{"fix":"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.","cause":"The MongoDB server is not running, is inaccessible from the application's host, or the connection URI is incorrect. This can be due to an incorrect host/port, firewall rules, or the MongoDB service not being started.","error":"pymongo.errors.ServerSelectionTimeoutError: <hostname>:<port>: [Errno 111] Connection refused, Timeout: 30s"},{"fix":"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`.","cause":"Incorrect username or password in the `MONGO_URI`, or the specified user does not have access to the database. For older MongoDB versions, it could also mean the database name was omitted from the URI while using credentials.","error":"pymongo.errors.OperationFailure: Authentication failed."}]}