To connect MongoDB with Flask in an Ubuntu machine, follow these steps:
Install the pymongo package:
pip install pymongo
Install Flask-PyMongo package:
pip install Flask-PyMongo
In your Flask app, add the following code to create a connection to your MongoDB:
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(app)
Note: Replace "myDatabase" with the name of your database.
Use the mongo object to interact with the database. For example, to insert a document into a collection, use the following code:
myCollection = mongo.db.myCollectionName
myCollection.insert_one({"name": "John", "age": 30})
Note: Replace "myCollectionName" with the name of your collection.
That's it! Now you can use Flask and MongoDB together in your Ubuntu machine.
Top comments (0)