How to connect MongoDB and Python?

Connecting to NoSQL Databases- Step by Step Tutorial

You are working on a Tkinter project and want to save the user details securely, you require a database. MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time. 

Why use MongoDB?

MongoDB offers faster query processing but with an increased load and system requirements. It provides good cloud services and good storage facilities for a free account. MongoDB is created using Binary JSON format (BSON) to support various data types. Data stored in BSON can be searched and indexed, tremendously increasing performance. MongoDB is easy to scale, and it uses internal memory for storing and accessing data. Check more about MongoDB.

Create a MongoDB Cluster – Step by Step Tutorial

1. Create your account on MongoDB. It’s free. 

2. Once your account is created, Build your first cluster. 

3.  Choose the Free shared host and select cloud service provider and region. (AWS is selected by default). This free service provides shared RAM with 512 MB storage. Build your first cluster. You can rename Cluster 0 and give it a name.


(Note: once your cluster is created you won’t be able to change its name)

4. Congrats, on building your first cluster.  Once you have named and created a cluster wait for 1-3 minutes, the new cluster takes some time to be created. Once it is created, click on Connect from the Atlas dashboard.


5. It then asks for an IP address, you can choose Access from anywhere and then enter your Username and password, it is different from your login details. But remember your database password and username, this is going to be required later. Then process by clicking to Choose the collection method.

6. Now, select Connect your application. Since we are using Python here, Choose Python with a 3.6+ later versions. Choose the Full driver example and copy the text that is displayed. This will be used in code.



7. Now close the window and Browse Collections. Select Add my own data.

8. Enter your Database name and Collection name.

Install pymongo

You followed all the steps, well done you have successfully created the database and collection, it’s time to add some information into it.

We will use Python to perform mongo CRUD operations, in order to do this install pymongo using pip. Open your terminal and type the command:

pip install pymongo

To check whether the module is imported, open the terminal and type python. Then run the following code.

import pymongo

If no error, you are good to go further.

Insert and Delete Documents in MongoDB using Python Tkinter

Tkinter is one of the easiest ways to implement GUI applications. Tkinter is a Python library that provides a good range of widgets where you can design amazing GUI applications. Now using this let us implement MongoDB. We will store the name and email ids in our database. For asking the user their name and email, you can create an Entry box using Tkinter. After configuring the entry box, create a button that stores the information in our database.

MongoDB supports CRUD operations which means create, read, update, and delete operations. We will be focusing on Inserting and Deleting operations using Tkinter.

Connect MongoDB and Tkinter

import pymongo
import tkinter as tk
from tkinter import StringVar, messagebox


def database():
    try:
        #replace username and password into your details
        client = pymongo.MongoClient("mongodb+srv://<username>:<password>@blog.nwryh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
        db = client['your_database_name'] #creating a databbse
        #db = client.your_database_name  #other way to create database
        collection = db['your_collection_name']  #create a collection from the database
        return collection  #return database so that functions from button can perform CRUD operation
    except pymongo.errors.ConfigurationError:
        #database can be accessed only if you have active internet connection, this will prompt user the error, if user is not connected to internet
        messagebox.showerror("Network Error","No internet connection")

First, import Tkinter and pymongo modules and paste the full driver code which you got while selecting an application. Replace your username and password with your database details. Once you have modified the client URL, now create the database and collection. There are two syntaxes to do this

   • client[“database_name”]

   • client.database_name

For the database and Collection name, use the names which you entered while creating sample data. 

Now create insert and delete the document from the database. Create a root Tkinter and configure the widgets which we require to make the GUI. Create 2 labels for name and email with 2 entry boxes. Then create 2 buttons for insertion and deletion. You can explore about Read(find()) and Update from MongoDB documentation, its simple.

def insert_db():
    document = dict()
    #get the entered details from the user
    document['name'] = name_entry.get()
    document['mail'] = mail_entry.get()

    #call the database function and get the collection, so that you can perform C-create/insert operation
    collect = database()
    collect.insert_one(document)
    messagebox.showinfo("Sucess","Data Inserted")
    clear()

def delete_db():
    document = dict()
    document['name'] = name_entry.get()
    document['mail'] = mail_entry.get()
    collect = database()

    #call the database function and get the collection, so that you can perform D-delete operation
    collect.delete_one(document)
    messagebox.showinfo("Sucess","Data Deleted")
    clear()

#this function is used to clear the entry box once the data is inserted and deleted
def clear():
    name_entry.delete(0,"end")
    mail_entry.delete(0,"end")
    name_entry.focus_set()

#create a Tkinter GUI application
root = tk.Tk()
root.geometry('430x360+410+200')
root.title("Learn MongoDb")
root.resizable(False,False)

#canvas widget is used to design tkinter GUI, you can add background image, bg color, good scroll bar and etc..
canvas = tk.Canvas(bg="aqua")
canvas.place(x=-1,y=-1,width=460,height=460)

#I suppose this is self-explanary
name = tk.Label(text="Enter your name:",font=("arial",15,"bold")).place(x=10,y=50)
gmail= tk.Label(text="Enter your mail:",font=("arial",15,"bold")).place(x=10,y=110)

name_var = tk.StringVar()
email_var = tk.StringVar()

global name_entry,mail_entry
#get user details to store in database
name_entry = tk.Entry(bd=5,textvariable=name_var,bg="yellow")
name_entry.place(x=180,y=45,width=220,height=45)

mail_entry = tk.Entry(bd=5,textvariable=email_var,bg="yellow")
mail_entry.place(x=180,y=105,width=220,height=45)

#create two buttons for insertion and deletetion operation
insert_btn = tk.Button(bd=4,bg="blue",fg="white",command=insert_db,text="Insert",font=("arial",15,"bold")).place(x=120,y=200)
delete_btn = tk.Button(bd=4,bg="blue",fg="white",command=delete_db,text="Delete",font=("arial",15,"bold")).place(x=250,y=200)

root.mainloop()

Download source code on GitHub.

For complete MongoDB tutorial. Check out this documentation.