Working with MongoDB

Jack Arokiason J
featurepreneur
Published in
3 min readMay 2, 2021

About the Article

  1. Introduction
  2. MongoDB Atlas
  3. flask and MongoDB

Introduction

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License

Mongodb is a NoSQL Database

MongoDB Atlas

Create a Cloud Database on MongoDB Atlas

MongoDB Atlas is the official cloud database service offered by MongoDB. Though we could set up an instance of MongoDB locally, getting started with Atlas is much simpler. We’ll be using its free tier.

Once you’ve logged in successfully, you should create your first project (feel free to name it whatever you like).

Next, click ‘Build a New Cluster’. You should see a screen like this:

Make sure to choose a region that is labeled ‘Free Tier Available’. Then scroll down and choose the ‘M0 Sandbox’ tier. This is completely free, and you’re allowed one free cluster per account.

In this tutorial, we’ll keep the default cluster name: ‘Cluster0’.

Set User Permissions

We now need to define users and set permissions. In the navigation menu on the left, click ‘Database Access’, then click ‘Add New User’. For this tutorial, we’ll create a user called ‘sample’ with a password ‘sample’. (For your own projects, I recommend much more secure credentials!)

Set Network Permissions

Here is the first obstacle that caused me a lot of issues at the beginning: In order to access your database, you need to whitelist certain IP addresses.

Since I work remotely in lots of different places, my IP address kept changing and so my database wouldn’t connect. It took me far too long to realize that the problem was network permissions!

If you know your IP address will always be the same, just whitelist your own IP. If you move around like me, you can use the 0.0.0.0/0 IP address to allow access from any IP. Since this is less secure, it may be sensible to save this as a temporary whitelist, as in the image below:

Get URI

Finally, go back to the ‘Clusters’ page and, under the name of your cluster, click ‘Connect’.

From the options, choose ‘Connect Your Application’ and you’ll get a connection URI like so:

Flask and MongoDB

from flask import Flask
from flask_pymongo import PyMongo
from decouple import config
app = Flask(__name__) app.config['MONGO_URI'] = config('MONGO_URI') mongo = PyMongo(app)
collection = mongo.db.student_name
@app.route('/')
def flask_mongodb_atlas():
return "flask mongodb atlas!"
@app.route("/test")
def test():
collection.insert({"Name": "Smith",
"Bid": "18cr",
"review": "good bowler"
})
return "Connected to the data base!" if __name__ == '__main__':
app.run(port=8003, debug=True)

Thank you!!!

--

--