MongoEngine、django-mongo-engine与PyMongo的区别及Django2.0连接MongoDB咨询
Hey there! Let's start by breaking down the roles of these three tools, then walk you through setting up Django 2.0 with MongoDB on Python 3.6.
1. PyMongo: The Low-Level Foundation
PyMongo is MongoDB's official, low-level Python driver. It lets you interact directly with MongoDB using raw BSON (Binary JSON) queries, giving you full control over every database operation.
- You write explicit commands like
collection.find({"name": "Alice"})orcollection.insert_one({"title": "My First Post"}) - It's the base layer that all higher-level MongoDB tools in Python rely on
- Ideal if you need fine-grained control over indexes, query optimization, or low-level database interactions—but it requires writing more boilerplate code
- Doesn't integrate with Django's ORM out of the box; you'd have to build custom adapters to use it with Django workflows
2. MongoEngine: The Object-Document Mapper (ODM)
MongoEngine is an ODM—think of it as MongoDB's equivalent to Django's ORM. It sits on top of PyMongo and maps MongoDB documents to Python classes, making database interactions more intuitive and Pythonic.
- You define document schemas as Python classes (e.g.,
class Post(Document): ...) - Use object-oriented methods like
post.save()orPost.objects.filter(title__contains="Django")instead of raw BSON - Abstracts away low-level PyMongo details to speed up development
- Works with any Python project, but isn't purpose-built for Django—integrating it with Django's admin, auth, or forms requires extra work
3. django-mongo-engine: Django-Friendly Integration
django-mongo-engine is a Django-specific adapter for MongoEngine. It wraps MongoEngine to fit seamlessly into Django's ecosystem, letting you use MongoDB with Django just like you would a relational database.
- Supports core Django features: admin interface, authentication system, form handling, and template integration
- Uses Django-style model definitions (backed by MongoEngine's ODM)
- Handles the bridge between Django's ORM hooks and MongoDB, so you don't have to build custom integrations
- Perfect if you want to use MongoDB as your Django database without sacrificing Django's productivity tools
Since you're using older versions (Python 3.6, Django 2.0), you'll need to install compatible package versions (newer releases drop support for these toolchains). Here's your step-by-step guide:
Step 1: Install Required Packages
Run this command to get versions that work with your stack:
pip install django-mongo-engine==0.9.0 pymongo==3.12.0
django-mongo-engine==0.9.0is the last version that supports Django 2.0pymongo==3.12.0is compatible with Python 3.6 and pairs perfectly with the above adapter
Step 2: Configure Django Settings
Open your project's settings.py and replace the default DATABASES block with this MongoDB configuration:
DATABASES = { 'default': { 'ENGINE': 'django_mongo_engine', 'NAME': 'your_database_name', # Name of your MongoDB database 'HOST': 'localhost', # Use remote IP if your MongoDB is hosted elsewhere 'PORT': 27017, # Default MongoDB port # Uncomment below if your MongoDB requires authentication # 'USER': 'your_db_username', # 'PASSWORD': 'your_db_password', } }
Step 3: Define Your Models
Instead of inheriting from Django's models.Model, use django_mongo_engine.Document for top-level documents, or EmbeddedDocument for nested data:
# myapp/models.py from django_mongo_engine import Document, fields class Author(Document): name = fields.StringField(required=True, max_length=100) email = fields.EmailField(unique=True) class BlogPost(Document): title = fields.StringField(required=True, max_length=200) content = fields.StringField() pub_date = fields.DateTimeField(auto_now_add=True) author = fields.ReferenceField(Author) # Links to an Author document
Step 4: Use Django Admin (Optional)
Register your models with Django's admin just like you would with a relational database:
# myapp/admin.py from django.contrib import admin from .models import Author, BlogPost admin.site.register(Author) admin.site.register(BlogPost)
Step 5: Run Your Project
MongoDB is a document database, so you don't need to run Django's migrate commands (there are no table schemas to create). Just start the server:
python manage.py runserver
Quick Tips for Your Stack
- For complex operations that need raw PyMongo power, access the underlying collection via
YourModel.objects.collection(e.g.,BlogPost.objects.collection.find({"title": {"$regex": "Django"}})). - Keep in mind that some Django features (like complex database transactions) aren't fully supported by MongoDB, so plan accordingly for critical workflows.
内容的提问来源于stack exchange,提问作者Prashantkumar K B

