How to integrate Django with MongoDB?

In today’s tech-freak world companies want a storage system that offers enough scalability, performance, and flexibility. That’s why Data experts are using MongoDB to execute Data Analysis and Visualization with ease. Python is a popular programming language among developers because of its simple yet powerful capabilities. As a result, Django, a Python framework, is widely used in most current software companies.

Django users are now turning to MongoDB to store data related to application development. They want to integrate Django with MongoDB to speed up their application development. In this article, we will discuss 3 methods through which we can integrate Django with MongoDB

Introduction to Django

Django is a high-level Python Web framework that promotes rapid development and simple, practical design. It’s built by professional developers to take care of a lot of the troubles of Web development so that they can concentrate on developing apps instead of reinventing the wheel. It’s open-source and free. Django was created to develop almost any type of website, and it has the ability to recognise almost any format, including HTML, RSS feeds, JSON, XML, and others.

Introduction to MongoDB

MongoDB is an open-source NoSQL database based on C++. It allows you to store data without being restricted by the Data Structure or the type of fields. This document-oriented storage uses a Dynamic Schema to store data and uses the JSON format. Furthermore, MongoDB Documents are meant to seem like JSON objects, allowing you to operate in a familiar environment while using MongoDB.

Methods to integrate Django with MongoDB

The Django MongoDB Integration can be easily set up using the following three methods:

Method 1 – Using MongoEngine to setup Django MongoDB integration

This method is one of the most used Mapper tools for mapping MongoDB documents with Python. Steps to be followed to setup are –

Step 1: Install MongoEngine

To install mongodb use the below statement on python editor-

pip install -u mongoengine

Step 2: Customize

Start your Django project and enter the following code into the file.

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

Make a comment in the DATABASES section of the above code.

Step 3: Import Project Documents

In your file, add the following code to import the needed Documents from the MongoEngine:

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

Your Mongoengine Django MongoDB Integration is now complete.

Method 2 – Using Djongo to Set Up MongoDB Integration

Djongo connects to a MongoDB database rather than creating one. As a necessity, you must have a MongoDB database set up. Let’s start by setting up the MongoDB database. Djongo functions as a SQL-to-MongoDB transporter and assists in connecting to this database.

Step 1: Install MongoDB Compass on your system after downloading it. Then, in MongoDB, click the “new database” button to build a NoSQL database.

Step 2: Install the Django package and create a project

To install the Django Package, type the following command in your terminal or git bash:

pip install django

Install Djongo –

pip install djongo

Then, using the following command, create a new Django Project at your selected location:

django-admin startproject mysite

Step 3: Customize the file

Add the following database setting in the file

#If your database is in your local machine
   ‘default’: {
      ‘ENGINE’: ‘djongo’,
      ‘NAME’: ‘your-db-name’,
      ‘USER’: ‘root’,               # Database User name <optional>

At last, execute the following command-

python3 migrate

After following all these steps your setup of integration using Djongo will be complete.

Method 3 – Using PyMongo to Set Up Django MongoDB Integration

PyMongo keeps track of the Python distribution needed to work with MongoDB. It’s a tool for writing and saving JSON data to and from your MongoDB database.

Step 1: To use PyMongo to integrate Django with MongoDB, first install PyMongo on your system:

pip install pymongo

Step 2: Following the initialization of the Django project, Add the following lines of code to in the project folder:

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

Step 3: As illustrated in the code below, you can now write data in the file in your MongoDB using the following function:

from project.utils import get_db_handle, get_collection_handle
db_handle, mongo_client = get_db_handle(DATABASE_NAME, DATABASE_HOST, 
collection_handle = get_collection_handle(db_handle, REGIONS_COLLECTION)

With the writing of the above code, your integration using PyMongo will be complete.