This article was published as a part of the Data Science Blogathon
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:
Now without further ado let’s start……
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.
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.
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.
Source: myself
In this article, we will focus on the Djongo method in detail.
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.
pip install -u mongoengine
Make sure you have the above requirements installed before proceeding to the next steps.
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.
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
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.
pip install pymongo
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
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…..
Go to the official website of MongoDB and download the MongoDB community server.
Source: https://www.mongodb.com/try/download/community
Please follow the below-mentioned link to download and install MongoDB Compass.
Source: https://www.mongodb.com/try/download/compass
After installation is complete open MongoDB Compass on your system and creates MongoDB or NoSQL Database as shown below.
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.
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
Go to the location of your choice and create a Django project using the below command in the terminal:
django-admin startproject mysite
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’, } }
python3 manage.py migrate
If you do not see any error message then you have successfully connected to MongoDB using djongo.
That’s it.. 🙂
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.
hello, Its's nice to see mongodb is connected with django but doesn't support completely. I explain why so because when you install any third party packages to your project it could written for Django models not Djongo which will fall you in Database error while migrating you apps. Do we have any solution for this case?
Nice article, thanks for sharing. Could you please also write an article about how we can use Foreign Key, Many to Many Relationships, etc, that we generally use in Django SQL Database.