DEV Community

Cover image for Simple Steps to Connect Flask App with MongoDB in an Ubuntu Machine
Prashant Dwivedi
Prashant Dwivedi

Posted on

Simple Steps to Connect Flask App with MongoDB in an Ubuntu Machine

To connect MongoDB with Flask in an Ubuntu machine, follow these steps:

Install the pymongo package:

pip install pymongo
Enter fullscreen mode Exit fullscreen mode

Install Flask-PyMongo package:

pip install Flask-PyMongo
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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})


Enter fullscreen mode Exit fullscreen mode

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)