Overview
In this guide, you can learn how to modify your Djongo project to use Django MongoDB Backend. Djongo is a third-party library that translates SQL queries into MongoDB Query Language (MQL) queries, allowing you to use MongoDB as your Django backend for Django versions 4.0 and earlier. However, Django MongoDB Backend is the officially supported integration and offers more comprehensive Django support, expanded access to MongoDB features, and compatibility with newer Django versions.
This guide shows how to migrate a Djongo application to Django MongoDB Backend by updating the following application components:
Database Settings
To connect to MongoDB by using Django MongoDB Backend instead of Djongo,
modify the DATABASES setting in your application's settings.py file.
Update the value of this setting's nested ENGINE key from "djongo" to
"django_mongodb_backend". Then, specify your connection string in the
nested HOST key instead of the CLIENT key.
Tip
To learn more about the DATABASES setting, see the
Configure Your Database Connection guide.
Example
The following example shows how to modify your DATABASES setting to use
Django MongoDB Backend. Select the Djongo tab to see the initial setting
configuration, and select the Django MongoDB Backend tab to see the
updated setting:
DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://cluster0.example.mongodb.net', }, 'NAME': 'my_database' } }
DATABASES = { 'default': { 'ENGINE': 'django_mongodb_backend', 'HOST': 'mongodb+srv://cluster0.example.mongodb.net', 'NAME': 'my_database' }, }
Model Definitions
To update your models to use Django MongoDB Backend, make the following changes to your model definitions:
Import the
modelsmodule fromdjango.dbinstead of fromdjongo.Remove explicit
ObjectIdFielddefinitions, because Django MongoDB Backend automatically creates an_idfield of typeObjectIdField.Modify the syntax of MongoDB-specific array and embedded fields.
Important
Field Types
Djongo and Django MongoDB Backend likely store Django fields in the same format. However, you might experience incompatibilities due to differences in the integrations' field converters. If you encounter any issues, you can submit feedback by using the Rate this page tab on the right side of this page.
Tip
To learn more Django MongoDB Backend models, see the Create Models guide.
Single Model Example
The following example shows how to update a model class
named Recipe for compatibility with Django MongoDB Backend. Select the
Djongo tab to see the initial model, and select the
Django MongoDB Backend tab to see the updated model:
from djongo import models class Tag(models.Model): data = models.CharField(max_length=100) class Meta: abstract = True class Recipe(models.Model): _id = models.ObjectIdField() title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) tags = models.ArrayField(model_container=Tag)
from django.db import models from django_mongodb_backend.fields import ArrayField class Recipe(models.Model): title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) tags = ArrayField( models.CharField(max_length=100), size=4, null=True, blank=True)
To create a Recipe object that stores the preceding fields,
use the following code:
Recipe.objects.create( title="Tiramisu", cuisine="Italian", cook_time=20, tags=[ {"data": "dessert"}, {"data": "classic"}, {"data": "espresso"}, {"data": "chocolate"} ] )
Recipe.objects.create( title="Tiramisu", cuisine="Italian", cook_time=20, tags=["dessert", "classic", "espresso", "chocolate"] )
Embedded Model Example
When using Djongo, you can use an EmbeddedField to represent an
embedded MongoDB document. To define a field that stores multiple embedded
documents, you can use an ArrayField.
Django MongoDB Backend provides the following fields that represent embedded documents:
EmbeddedModelField: Stores a nested modelEmbeddedModelArrayField: Stores an array of nested models
Tip
Model Polymorphism
You cannot use Djongo fields to store an array of multiple model types.
However, Django MongoDB Backend provides the PolymorphicEmbeddedModelField
and PolymorphicEmbeddedModelArrayField fields to support polymorphism.
To learn more, see Use Advanced Fields in the Create Models guide.
The following example shows how to update a models.py file that defines a
Recipe model containing the following embedded model fields:
nutrition: Stores one embeddedNutritionmodel that represents nutrition informationreviews: Stores multiple embeddedReviewmodels that represent individual recipe reviews
Select the Djongo tab to see the initial models, and select the Django MongoDB Backend tab to see the updated models:
from djongo import models class Nutrition(models.Model): calories = models.IntegerField(default=0) carb_grams = models.IntegerField(default=0) protein_grams = models.IntegerField(default=0) class Meta: abstract = True class Review(models.Model): author = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Meta: abstract = True class Recipe(models.Model): _id = models.ObjectIdField() title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) nutrition = models.EmbeddedField(model_container=Nutrition) reviews = models.ArrayField(model_container=Review)
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelField, EmbeddedModelArrayField class Nutrition(EmbeddedModel): calories = models.IntegerField(default=0) carb_grams = models.IntegerField(default=0) protein_grams = models.IntegerField(default=0) class Review(EmbeddedModel): author = models.CharField(max_length=100) rating = models.IntegerField(default=0) class Recipe(models.Model): title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) nutrition = EmbeddedModelField(Nutrition, null=True, blank=True) reviews = EmbeddedModelArrayField(Review, null=True, blank=True)
Indexes
To update the indexes in your Djongo app for Django MongoDB Backend compatibility, you must use the index classes provided by Django MongoDB Backend.
Djongo provides separate classes to represent each MongoDB index, including classes for single field indexes, compound indexes, multikey indexes, and more.
Django MongoDB Backend provides the following three classes to represent all index types:
Indexclass: Django's index class, which represents all non-Search index typesSearchIndexclass: A Django MongoDB Backend-specific class to represent MongoDB Search indexesVectorSearchIndexclass: A Django MongoDB Backend-specific class to represent MongoDB Vector Search indexes
Tip
To learn more about how to use Django MongoDB Backend to create indexes, see the Create Indexes guide.
Example
The following example shows how to update a compound index on a Recipe model. The
Django MongoDB Backend implementation also adds a MongoDB Search index,
which Djongo does not support. Select the Djongo tab to see the initial
index, and select the Django MongoDB Backend tab to see the
updated indexes:
from djongo import models from djongo.models.indexes import CompoundIndex class Recipe(models.Model): _id = models.ObjectIdField() title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) class Meta: indexes = [ CompoundIndex(fields=["title", "cook_time"]) ]
from django.db import models from django_mongodb_backend.indexes import SearchIndex class Recipe(models.Model): title = models.CharField(max_length=100) cuisine = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) class Meta: indexes = [ models.Index(fields=["title", "cook_time"]), SearchIndex(fields=["cuisine"], name="cuisine_search_idx") ]
Queries
You can use Django's QuerySet API to
query both Djongo and Django MongoDB Backend models. However, the syntax differs
for embedded model queries.
Djongo treats embedded models as Python dictionaries, and you must use Python dictionary syntax to access or modify their fields. Django MongoDB Backend treats embedded models as Django models, so you use the same syntax for interacting with their fields as with all other models.
Important
Performance Regressions
Djongo and Django MongoDB Backend queries generate different underlying MQL queries, which might have performance implications. When migrating from Djongo to Django MongoDB Backend, we recommend that you monitor performance changes to identify potential regressions and file a JIRA ticket if you discover any.
Tip
To learn more about how to use Django MongoDB Backend to query your models, see the Specify a Query guide.
Example
The following example shows the difference between a Djongo and a Django MongoDB Backend
query on the Recipe model and its nutrition embedded model field,
defined in the Embedded Model Example section.
The code queries the Nutrition embedded model's calories field.
Select the Djongo tab to see the initial
query, and select the Django MongoDB Backend tab to see the
updated query:
Recipe.objects.filter(nutrition__lt={'calories': 500})
Recipe.objects.filter(nutrition__calories__lt=500)
Transactions
Both Djongo and Django MongoDB Backend support Django's atomic transaction API functionality. However, they each provide a custom API to implement this functionality. You can update your transactions for Django MongoDB Backend compatibility by modifying your code's import statement.
Tip
To learn more about how to use Django MongoDB Backend to perform transactions, see the Transactions and Sessions guide.
Example
The following example shows how to update your code to import Django MongoDB Backend's transaction API. Select the Djongo tab to see the initial statement, and select the Django MongoDB Backend tab to see the updated statement:
from djongo import transaction
from django_mongodb_backend import transaction
Migrations
Djongo does not support database migrations and does not enforce
schema validation by default. If you set the ENFORCE_SCHEMA setting
to True in your settings.py file, Djongo enforces MigrationErrors
when retrieved documents have missing field values.
Django MongoDB Backend supports database migrations with some limitations. To learn more about these limitations, see Migration Support in the Feature Compatibility guide.
Django MongoDB Backend does not enforce schema validation. As a result, updating model fields without running migrations to update the database schema does not generate errors.
Additional Information
To learn how to set up a new application that uses Django MongoDB Backend, see the Get Started tutorial.
To learn more about running database operations by using Django MongoDB Backend, see the Perform CRUD Operations guide.
To learn more about creating Django MongoDB Backend models, see the Create Models guide.