Learn everything about Analytics

Home » How to connect MongoDB database with Django

How to connect MongoDB database with Django

This article was published as a part of the Data Science Blogathon

Introduction

Let’s consider a scenario where you are working on a real-time project. The data you have to work on is unstructured and has millions of records.  This is where MongoDB comes into the picture. It can store unstructured data with easy access to it. Now that we have a basic understanding let’s explore a little bit in-depth about MongoDB and Django.

At the end of this article you will have a basic understanding of the following:

  • What is MongoDB?
  • What is Django?
  • Methods to connect with MongoDB using Django.

Now without further ado let’s start……

1. What is MongoDB?

First, let’s see the official definition…

MongoDB is a document database, which means it stores data in JSON-like documents. We believe this is the most natural way to think about data and is much more expressive and powerful than the traditional row/column model.

Source: https://www.mongodb.com/

In simple words…. the traditional way of storing and using any data is structured (table or row/column format). But in real-time, this is not how data is received or stored. Data can have any number of fields or parameters to store. MongoDB stores the data in a similar format using JSON-like documents and NoSQL is used to access the stored data.

2. What is Django?

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

Source: https://www.djangoproject.com/

Django was designed to build websites of almost any type and because of it’s a property that it understands almost any format including HTML, RSS feeds, JSON, XML, etc. it can also be used to connect with MongoDB because MongoDB also uses JSON like format.

Now we will see different ways to connect with MongoDB and explore connecting to MongoDB using Django in detail.

3. Methods to connect with MongoDB using Django

There are three different ways to connect with MongoDB using Django easily as shown in below figure. Let’s see each method one by one.

connect mongodb with django

Source: myself

In this article, we will focus on the Djongo method in detail.

3.1 MongoEngine

MongoEngine is a Document-Object Mapper (think ORM but for document databases) for working with MongoDB from Python. (Source: http://mongoengine.org/#home)

Let’s see how to set up MongoEngine and connect with MongoDb using it.

Step 1: Installation:

pip install -u mongoengine

Step 2: Requirements:

  1. MongoDB 3.4, 3.6, 4.0 (https://www.mongodb.com/try/download/community)
  2. pymongo>=3.4 (https://pypi.org/project/pymongo/)

Make sure you have the above requirements installed before proceeding to the next steps.

Step 3: project/settings.py 

After starting the Django project open the settings.py file and add these lines to it. Also, remove or comment out the DATABASES section as shown in the below code snippet.

import mongoengine
mongoengine.connect(db=DATABASE_NAME, host=DATABASE_HOST, username=USERNAME, password=PASSWORD)
#DATABASES = {
# 'default': {
# 'ENGINE': 'djongo', #'django.db.backends.sqlite3',
# 'NAME': 'blogs', # DB name
# 'USER': 'root', # DB User name <optional>
# }
#}

No need to do migrate and makemigrations because you are using MongoEngine ORM.

Also, your models.py file will look as shown in below code snippet.

Step 4: project/models.py

from mongoengine import Document, fields
class Blogs(Document):
   name = fields.StringField()
   topic = fields.StringField()
   date = fields.DateTimeField()
   addition_info = fields.DictField()

Now, you are ready to go and also you can check more about MongoEngine here http://docs.mongoengine.org/ and https://github.com/MongoEngine/mongoengine

3.2 PyMongo

This is a tool that contains python distribution for working with MongoDB. This is good for writing and saving JSON data to your MongoDB. This tool will let you use all of the mongo queries in your code.

Let’s see the step to set up pymongo and connect to MongoDB using this approach.

Step 1: Installation:

pip install pymongo

Step 2: project/utils.py

After starting the Django project do the following:

Create utils.py in the project folder and add these lines

from pymongo import MongoClient
def get_db_handle(db_name, host, port, username, password):
    client = MongoClient(host=host,
                         port=int(port),
                         username=username,
                         password=password
                        )
    db_handle = client[db_name]
    return db_handle, client
def get_collection_handle(db_handle,collection_name):
    return db_handle[collection_name]

Now, you can use the above-mentioned functions in your views.py file or anywhere you want to fetch or write data into your MongoDB

Step 3: project/views.py

from project.utils import get_db_handle, get_collection_handle
db_handle, mongo_client = get_db_handle(DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, USERNAME, PASSWORD)
collection_handle = get_collection_handle(db_handle, REGIONS_COLLECTION)
collection_handle.find({...})
collection_handle.insert({...})
collection_handle.update({...})

No need to do anything in project/models.py when you are using PyMongo. Also, no need to add anything in the project/settings.py but don’t forget to comment out the DATABASES part in the project/settings.py file.

3.3 Djongo

Here we will see how to install MongoDB, Django and connect using the Djongo method.

Let’s start…..

Step 1:  How to Install MongoDB

Go to the official website of MongoDB and download the MongoDB community server.

install mongodb

Source: https://www.mongodb.com/try/download/community

Step 2: How to Download MongoDB Compass

Please follow the below-mentioned link to download and install MongoDB Compass.

Source:  https://www.mongodb.com/try/download/compass

Step 3: Creating Database using MongoDB Compass

After installation is complete open MongoDB Compass on your system and creates MongoDB or NoSQL Database as shown below.

Install MongoDB With Compass On Windows - Vegibit

To create a database click on the ‘CREATE DATABASE’ button. Once you click the button, the demo database is created as shown in the below figure.

database created mongodb with django

Step 4: How to Install Django Package

Open the terminal or git_bash(if you are using Windows OS) and just type hit this command to install this package in your system.

pip install django

Step 5: Create Project

Go to the location of your choice and create a Django project using the below command in the terminal:

django-admin startproject mysite 

Step 6: Make changes in the settings.py file

Open the setting.py file and simply add this database setting

#If your database is in your local machine
DATABASES = {
   ‘default’: {
      ‘ENGINE’: ‘djongo’,
      ‘NAME’: ‘your-db-name’,
   }
}

Step 7: Execute migrate Command

python3 manage.py migrate

If you do not see any error message then you have successfully connected to MongoDB using djongo.

That’s it.. 🙂

Conclusion

In this article, we explore what is MongoDB, Django, and ways to connect with MongoDB using Django. I hope now you have a better understanding of the above-discussed topics.

Please feel free to reach out in a comment in case of any queries. Any feedback is welcomed and will help me to improve the content of my article.

Have a great day … : )

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

You can also read this article on our Mobile APP Get it on Google Play