Ankaj Gupta
January 01, 2021

How to connect MongoDB with Django

How to Connect Django with MongoDB

In this article, you will learn how to connect a MongoDB database to a Python web application framework Django. You will also learn how to edit your Django Project Settings file and connect your web application to a MongoDB (NoSQL or document) Database.

Django is a flexible framework for quickly creating Python applications. By default, Django applications are configured to store data into a lightweight SQLite database file.

how to connect django with mongodb

Introduction

Django is used in such an amazing modular style, it's simple to replace different components of a Django-based web application. Because document (NoSQL) databases are more common these days, you might want to try running an application with a different backend rather than one of the standard relational databases such as MySQL, SQLite, PostgreSQL, etc.

3 Ways to Connect Django with MongoDB

1. Djongo

Extension to Django ORM framework

2. MongoEngine

ORM layer on top of PyMongo

3. PyMongo

Official MongoDB driver

1. Djongo

Djongo is an open-source project and regularly maintained. Djongo is a smarter approach to pymongo programming. It is an extension to the traditional Django ORM framework. It maps Python objects to MongoDB documents, a technique popularly referred to as Object Document Mapping or ODM.

Let's start connecting "Django" with "MongoDB" using djongo:

Step 1: Install Djongo

To set up the environment for Djongo, you first need to install the package:

pip install djongo

Step 2: Update settings.py

Go to the settings.py file of your Django App. Under the settings file for Databases, change the settings from SQLite3 or your current database to the following code:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'your-db-name',
        'CLIENT': {
            'host': 'localhost',
            'port': 27017,
            'username': '',
            'password': ''
        }
    }
}

Step 3: Run Makemigrations

Run makemigrations command to convert all the models into queries for the database:

python manage.py makemigrations

Step 4: Run Migrate

Run migrate command to migrate these changes into our database:

python manage.py migrate

Congratulations! Your Django project is now connected with MongoDB. Have fun!

Requirements

  • Python 3.6 or higher
  • MongoDB 3.4 or higher
  • If your models use nested queries or sub-querysets, MongoDB 3.6 or higher is required
inner_query = Blog.objects.filter(name__contains='Ch').values('name')
entries = Entry.objects.filter(blog__name__in=inner_query)

Note: Django doesn't create a MongoDB database. You must have a pre-made MongoDB database. If not, create a new database in MongoDB. Djongo helps to connect to that database and acts as a transpiler from SQL to MongoDB.

2. MongoEngine

MongoEngine is an ORM (Object Relation Mapping) layer on top of PyMongo written in Python. Using MongoEngine will grant you additional benefits like fields DictField and ListField which you will find very useful when dealing with unstructured JSON data in MongoDB.

Let's start connecting "Django" with "MongoDB" using MongoEngine:

Step 1: Install MongoEngine

To set up the environment for MongoEngine, you first need to install the package:

python -m pip install -U mongoengine

Step 2: Update settings.py

After that, open your project settings.py, and change the DATABASES part to this code:

# DATABASES={
#     'default':{
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

import mongoengine
mongoengine.connect(
    db='DATABASE_NAME',
    host='DATABASE_HOST',
    username='USERNAME',
    password='PASSWORD'
)

Requirements

  • MongoDB 3.4, 3.6, or 4.0
  • pymongo>=3.4

Note: You do not need to do makemigrations and migrate since you are not using Django ORM here.

3. PyMongo

PyMongo is a Python distribution containing tools for working with MongoDB. PyMongo is the recommended way to work with MongoDB from Python. It is great for writing and saving JSON data to your MongoDB, and it will let you use all of the MongoDB queries in your Python code.

Step 1: Install PyMongo

pip install pymongo

# To get a specific version of pymongo:
python -m pip install pymongo==3.5.1

# To upgrade using pip:
python -m pip install --upgrade pymongo

Step 2: Create utils.py

Create a utils.py file in your project root directory (project/utils.py) 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]

You can use the above functions in your views or anywhere you want to fetch or write data into your MongoDB.

Note:

  • You don't need anything in models when you are using PyMongo.
  • Also, no need to add anything in Settings.py but don't forget to comment out the DATABASES part.

Comparison: Which Method to Choose?

Method Best For Pros Cons
Djongo Full Django ORM support Works with existing Django models, migrations supported Less active development, may have compatibility issues
MongoEngine Flexible document modeling Great for complex schemas, ORM-like interface No Django admin support, different API
PyMongo Direct MongoDB access Full control, official driver, most flexible Manual query handling, no ORM features

Summary

You now know three different methods to connect Django with MongoDB:

  1. Djongo: Use if you want full Django ORM compatibility with MongoDB
  2. MongoEngine: Use if you need flexible document modeling with an ORM-like interface
  3. PyMongo: Use if you want maximum flexibility and control over your MongoDB operations

Choose the method that best fits your project requirements and team's familiarity with Django patterns.

django django and mongodb

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts