Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 77 ยท Models and the ORM

Django and NoSQL (MongoDB)

Can Django use MongoDB? Learn what the ORM supports, the official MongoDB backend and other options, how JSONField gives document-style data in SQL, and when relational is the better choice.

"Should I use MongoDB with Django?" is one of the most common questions from learners. The honest answer has two parts: it is possible and officially supported today, and for most projects it is not the best first choice. This lesson explains why, so you can decide with facts instead of fashion.

You will see what Django's ORM is built for, the main ways to connect Django to a document database such as MongoDB, how much "NoSQL flexibility" you already get from a relational database through JSONField, and a side-by-side comparison of the two modeling styles that you can run in the browser. (MongoDB itself needs a server, so the live examples use Django's JSON support and SQLite, and the MongoDB-specific code is read-only.)

What Django's ORM assumes

Django was designed around relational databases. Its ORM builds SQL, and many built-in features lean on relational guarantees:

  • ForeignKey, ManyToManyField and joins (select_related) between tables,
  • migrations that create and alter tables and columns,
  • constraints and transactions that the database enforces,
  • the admin, forms and django.contrib.auth and contenttypes, all of which are models with relations underneath.

A document database stores documents (JSON-like objects, often nested) in collections, with no fixed schema and usually no joins. That is a different model, and any bridge between the two has to bend something. This is why the Django project itself ships only SQL backends (SQLite, PostgreSQL, MySQL/MariaDB, Oracle), while document-database support lives in packages maintained outside Django core.

The options

Option What it is Good for Trade-offs
PyMongo next to the ORM Use Django with SQL as usual, and talk to MongoDB with the official driver for a few specific datasets Logs, event streams, big flexible blobs, analytics; a small piece of an otherwise relational app Two data layers; no ORM, admin or forms for the Mongo data
django-mongodb-backend The official MongoDB-maintained database backend: set ENGINE to MongoDB, and use ORM models, querysets, the admin and forms A project that is committed to MongoDB and wants the Django ORM on top Fields such as EmbeddedModelField and ObjectIdAutoField are MongoDB-specific; not every relational feature exists; releases follow Django versions
Djongo An older third-party backend that translated SQL into MongoDB queries Existing projects that already use it Its last PyPI release was in 2024; check Django version support before choosing it for anything new
MongoEngine A separate "ODM" with its own model classes (not the Django ORM) Teams that want a Mongo-first API You lose the Django ORM, admin and ModelForm integration unless you add more packages
Stay relational and use JSONField PostgreSQL (or MySQL, SQLite) with flexible JSON columns where you need flexibility Most "my data is irregular" cases JSON is not as fast or ergonomic as a native document engine at huge scale

For MongoDB with the Django ORM, today's best-supported route is django-mongodb-backend. Its versions follow Django's (for example, a 6.1.x release targets Django 6.1) and it is marked production/stable on PyPI. A configuration looks like this; follow the project's official template and documentation for the full setup, because Django's built-in apps such as auth and admin need MongoDB-specific migrations:

Python
# settings.py (read-only; pip install django-mongodb-backend)
DATABASES = {
    "default": {
        "ENGINE": "django_mongodb_backend",
        "HOST": os.environ["MONGODB_URI"],          # mongodb://... or mongodb+srv://...
        "NAME": "shop",
    },
}
DEFAULT_AUTO_FIELD = "django_mongodb_backend.fields.ObjectIdAutoField"
Python
# shop/models.py (read-only)
from django.db import models
from django_mongodb_backend.fields import EmbeddedModelArrayField
from django_mongodb_backend.models import EmbeddedModel


class Review(EmbeddedModel):          # lives INSIDE a product document, no table or join
    author = models.CharField(max_length=60)
    stars = models.PositiveSmallIntegerField()


class Product(models.Model):
    name = models.CharField(max_length=80)
    reviews = EmbeddedModelArrayField(Review, null=True, blank=True)

The query side (Product.objects.filter(name__icontains="pen")) looks like any Django code. For the other routes, pip install pymongo and call MongoClient(uri)["shop"]["events"].insert_one({...}) directly.

How much flexibility do you already have in SQL?

Many people reach for MongoDB because "my products have different attributes" or "my data is nested". A relational database handles both through JSON columns. Django's JSONField works on SQLite, PostgreSQL, MySQL, MariaDB and Oracle, stores arbitrary nested data, and lets you filter and sort by values inside it. On PostgreSQL you can add a GIN index on the column for fast lookups, and use extra lookups such as contains.

The example uses JSONField for a product catalog where each product kind has different attributes, with no migration needed to add a new attribute:

Python Document-style data with JSONField

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rows have different keys, and the queries reach into them with the same double-underscore syntax you know from Lookups, Q Objects and F Expressions: a plain key (attributes__color), a nested path (attributes__screen__touch), a list index (attributes__tags__0), has_key, and comparisons such as __gte that work on numbers inside JSON. KT() pulls a key out so you can group or sort by it. (Features like contains on JSON are PostgreSQL-specific; SQLite does not support them, so the example avoids them.) For more on this field, see Raw SQL, Database Functions and JSON Fields.

Embedding versus relating: the real decision

Document databases encourage embedding: keep an order's line items inside the order document. Relational databases encourage relating: items are rows that point at an order and a product. Neither is universally right. The example models one order both ways so you can compare reads, cross-order questions, price history and integrity.

Python The same order, relational versus embedded

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What the output tells you:

Question Relational (A) Document (B)
Read one whole order Two queries (order and items) One query: the order is a single document
"How many pens were sold ever?" One SQL aggregate over an indexed foreign key Must load and scan every order in Python (or use the document database's own aggregation pipeline)
A product's price changes The order total changes because the item points at the live price The order keeps the price it was sold at, because the price was copied
An item refers to a missing product Rejected by the database Accepted; nothing validates inside the JSON

Two lessons come out of it. First, embedding wins when you almost always read the parent and children together and rarely query across parents, and it makes snapshots such as "the price at order time" natural. Second, relational design wins for cross-cutting questions and integrity. Note that a good relational shop also copies the price onto the OrderItem row (unit_price_cents), which gets the benefit of the snapshot without giving up the constraints. Many "NoSQL" advantages are really design choices that work in SQL too.

When NOT to use MongoDB with Django

Choose a relational database (usually PostgreSQL) when:

  • your data has clear relationships: users, orders, products, invoices. Most business applications do;
  • you need multi-row transactions and constraints to protect money or inventory;
  • you want the full Django ecosystem to just work: the admin, auth, contenttypes, third-party packages that assume SQL and migrations;
  • your team knows SQL, and your reporting tools talk SQL;
  • the real need is only "some flexible fields", which JSONField covers.

Consider a document database when:

  • the data is truly document-shaped (content blocks, catalogs with very different attributes per category, event payloads) and you read whole documents;
  • you must scale writes horizontally across many machines and have planned for the trade-offs;
  • you already operate MongoDB and have the expertise to run it well.

And remember that you do not have to choose just one: it is common to keep the core in PostgreSQL and add specialized stores around it, for example Redis for cache and sessions (see Caching) or a search engine for full-text search.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is the officially supported way to use the Django ORM with MongoDB today?

    Django core ships only SQL backends. MongoDB maintains django-mongodb-backend, which plugs into the ORM, with versions that follow Django.
  2. 2. What does Django's JSONField give you on SQL databases?

    JSONField stores nested data and supports key lookups and transforms, which covers many 'irregular data' needs without leaving SQL.
  3. 3. Which situation favors embedding items inside the parent document?

    Embedding is a single read and a natural snapshot. Cross-parent queries and integrity are the strengths of the relational layout.
  4. 4. What is the safest default for a typical business application built with Django?

    Relationships, constraints, transactions and the whole Django ecosystem are built around SQL, so PostgreSQL is the safe default.

Summary

  • Django's ORM, migrations, admin and contrib apps assume a relational database; document-database support comes from packages outside Django core.
  • For MongoDB you can use PyMongo beside the ORM, the official django-mongodb-backend, older options such as Djongo, or a Mongo-first library like MongoEngine.
  • JSONField gives schema-flexible, nested data in SQL, with key lookups and transforms, and often removes the need for a separate document store.
  • Embedding gives single-read documents and snapshots; relational design gives cross-record queries and database-enforced integrity. Choose by how the data is read.
  • Default to PostgreSQL; add MongoDB deliberately when the data is document-shaped or the scale demands it.

Next: Django Forms, the next chapter.