Chris Umbel

Using MongoDB as a Backend for Django with django-mongodb-engine

MongoDB logoI've been pretty taken with MongoDB of late. It's nearly disgusting how productive it is. However, like all database systems it's only as productive as the higher-level systems that interface with it.

Personally I've used it primarily from Java and Ruby on Rails (via MongoMapper) and from Python via PyMongo.

PyMongo essentially exposes MongoDB via Python dictionaries. Sure, it's plenty elegant and plenty pythonic but when it came to django I wanted was something more MongoMapper-like, an honest-to-goodness Object-Document-Mapper.

django logoMonths and months ago when I looked into the existence of a MongoDB driver for django all that turned up was dead, false-start projects, but after revisiting it recently django-mongodb-engine came to my attention. django-mongodb-engine is pretty much exactly what I was looking for. The authors describe it as, "a database backend that adds mongodb support to django". In this post I intend to introduce it to you.

I'm going to assume you're comfortable getting a django application started. If that's not the case please check out the official getting-started docs.


In order to leverage MongoBD from django you'll need the following software installed and operating:

  • Python - If you're reading this article odds are you already have it.
  • MongoDB - I guess this is somewhat self explanatory, but you'll need MongoDB itself.
  • django-norel - is a special version of django designed for use with non-relational database engines in general.
  • django tooblox - a general purpose utility library upon which django-mongodb-engine depends
  • mongodb-engine - the MongoDB driver for django.


Infrastructure in place I'll go ahead and create a django project named "testproj" with an application named "testapp". startproject testproj
cd testproj/ startapp testapp


Naturally the django project must be configured to talk to a specific database in

    'default': {
        'ENGINE': 'django_mongodb_engine',
        'NAME': 'mydatabase',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '27017',

Edit 2012-11-20: Older versions may require ENGINE to be 'django_mongodb_engine.mongodb'.


In said application you could create a model in like

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length = 64)
    content = models.TextField()

It looks like a standard old django model, right? Nothing fancy here, just a plain old model with plain old fields.

Note that it's important to not create and AutoField named "id" or things will blow up when saving. That's because Mongo wants to put a proper ObjectId in there.


We can then save some model data strait away from a django view.

from django.http import HttpResponse
from models import *

def testview(request):
  article = Article(title = 'test title',
    content = 'test content')

  return HttpResponse("



If you then peer into Mongo with a native javascript query query like


you'll find your document returned

{ "_id" : ObjectId("4cb4f9a01a8ff904fa000001"), "content" : "test content", "title" : "test title" }


of course it's a simple matter to query Mongo from django to retrieve a list of Article objects just like you would with a relational store.

articles = Article.objects.all()

Embedding Documents

Many document-database-esque features are covered as well, but I'll just touch on one here. With a minor alteration to our model

from django.db import models
from django_mongodb_engine.mongodb.fields import EmbeddedModel
from django_mongodb_engine.fields import ListField

class Comment(EmbeddedModel):
  name = models.CharField(max_length = 160)
  content = models.TextField()

class Article(models.Model):
  title = models.CharField(max_length = 160)
  content = models.TextField()
  comments = ListField()  

then we can embed Comment documents into Articles.

article = Article(title = 'test title', 
  content = 'test content')

article.comments.append(Comment(name = 'alice', description = 'foo bar'))
article.comments.append(Comment(name = 'bob', description = 'fun baz'))


Thanks to the hard work of others it's a simple matter for us to use MongoDB as a backend for django. To see some specific examples of non-relational-style features check out the tests from the django-mongodb-engine project.

Wed Oct 13 2010 01:14:48 GMT+0000 (UTC)

7 Comments Comment Feed - Permalink
i'm clearly understood from this above examples, thank u!!!
by Thanga Vignesh Raja on Mon Apr 16 2012 07:19:15 GMT+0000 (UTC)
<h1>nice job</h1>
by hdks on Fri Dec 14 2012 18:12:33 GMT+0000 (UTC)
django tooblox -> django toolbox
by Jakob Olsen on Fri Apr 12 2013 07:45:24 GMT+0000 (UTC)
by ascjlakdjf on Thu Nov 13 2014 02:42:47 GMT+0000 (UTC)
I'm new to django so i don't understand from the 'saving' part. if you can explain that part further and the javascript query. 
by junk on Fri Jul 17 2015 06:52:20 GMT+0000 (UTC)
<i>fuck u</i>
by yoyo on Wed Aug 12 2015 09:55:17 GMT+0000 (UTC)
The problems of cognitive and also electric motor abilities generated by Remeron has been shown to be additive regarding those produced by liquor. Accordingly, patients must be advised to avoid [url=]buy indocin[/url]  liquor while taking mirtazapine. The main problem with fat burning is that individuals are unable to preserve the development they achieved gradually and gain weight when they quit the therapy [url=]buy cipro without prescription[/url]  and come back to their regular consuming designs. Skin and Appendages: acne, alopecia, angioedema, wounding, dermatitis contact, dermatitis, facial rash, flushing, folliculitis, warmth rash, hot flushes, photosensitivity reaction, pruritus [url=]hydrochlorothiazide[/url]  genital, psoriasis, purpura, rash erythematous, rash maculopapular, vitiligo, urticaria. Do not begin any kind of brand-new medicines before you review this choice with your [url=]augmentin[/url]  health care supplier as interaction is feasible. It's additionally usually recommended for patients with fluid loyalty due to heart disease, liver condition, [url=]lisinopril hydrochlorothiazide[/url]  or other problem. Nifedipine is a yellow crystalline element, virtually insoluble [url=]propranolol[/url]  in water but dissolvable in ethanol. This medicine should be taken with caution by patients presently utilizing phenytoin, blood thinners, pain killers, rifampin, phenobarbital, cyclosporine, diuretics, ketoconazole or dental the hormone insulin [url=]buy antabuse online no prescription[/url]  or drugs for diabetes, in addition to those with misery, renal condition, liver condition, tuberculosis, weakening of bones, thyroid gland ailment, hypertension or diabetes, as a different dose could be needed. If you missed out on an amount - take it as quickly as you don't forget unless it's practically time to take one more one. In that instance you can simply miss the [url=]wellbutrin online[/url]  dosage missed out on and go back to the normal application timetable. It is feasible [url=]lasix[/url]  that some adverse effects of Norvasc might not have been stated. There is time for [url=]allopurinol[/url]  you to do some research, but why would certainly you do that if you can have all the info offered to you easily? Taking [url=]buy cheap tadalafil[/url]  Tetracycline throughout maternity may lead to yellowing of the baby's teeth later in life. Utilizing this medication with various other medications that [url=]cafergot[/url]  make you tired can intensify these effects. Some health problems that you have or that operate in your [url=]buy cheap lasix[/url]  family members could be contraindications for taking Vardenafil as they could hamper its performance. Sildenafil (Viagra) is the world's most well-liked medicine made use of for the procedure of male [url=]augmentin[/url]  impotence. The large availability of Cialis on the Internet has actually made it nearly impossible [url=]propranolol[/url]  to pick the drug store you are visiting look regarding. Nevertheless, the advantages of internet shopping are still obvious to everyone. You do not should have a prescribed and can constantly get as much Cialis as you require. The advantages of an on the internet pharmacy are obvious: you do not should feel embarrassed chatting concerning the issue to your medical professional, and you have an opportunity to save [url=]buy abilify[/url]  a great deal of money. Viagra blocks a chemical that avoids blood [url=]levaquin[/url]  circulation in to the penis therefore offering for a suitable and more stable erection. Pushtikrit- Shallaki Capsules renews all the systems [url=]augmentin xr[/url]  of the body Twachya- Boswellia serrata Capsules nurtures the skin, gives it healthy appearances and also benefits in skin illness. It boosts the pressor result of norepinephrine but obstructs [url=]buy celebrex without prescription[/url]  the pressor response of phenethylamine. Research studies recommend that Pamelor disrupts the transportation, release, as well as storage of catecholamines. You should not take Reglan if you are allergic to metoclopramide, or if you have bleeding or blockage in [url=]where buy indocin (indomethacin):[/url]  your tummy or intestines, epilepsy or various other seizure disorder, or an adrenal glandular lump (pheochromocytoma). Capoten В® (captopril tablet computers, USP) is a certain competitive prevention of angiotensin I-converting enzyme [url=]stromectol[/url]  (ACE), the enzyme in charge of the conversion of angiotensin I to angiotensin II. Before you begin the treatment it's suggested [url=]amoxicillin 500mg capsules uk[/url]  to see your wellness treatment company and review any health issues you have that may conflict with the procedure. Vytorin (ezetimibe and simvastatin) [url=]where buy indocin (indomethacin):[/url]  is a medicine that incorporates 2 energetic ingredients, both of which have unique cholesterol-lowering homes. This medicine is known to have an effect on the health of a coming kid. In certain, Tetracycline can cause [url=]sildenafil[/url]  yellowing of the teeth by hampering their formation. Those moderate adverse effects could have to be monitored, yet do [url=]cheap tadalafil[/url]  not have to be managed in any kind of way. 
by JefferybozY on Fri Oct 02 2015 14:35:43 GMT+0000 (UTC)
Add a comment
E mail (Private)
Follow Chris
RSS Feed