How to connect django 5 with mongodb

To connect Django with MongoDB, you can use a Python library called django-mongodb-engine or djongo. Both of these libraries provide a MongoDB backend for Django’s Object-Relational Mapping (ORM) layer, allowing you to use MongoDB as your database for Django applications

Install the Library

pip install django-mongodb-engine

Configure Django Settings

In your Django project’s file, add the following:

    'default': {
        'ENGINE': 'django_mongodb_engine',
        'NAME': 'your_database_name',
        'HOST': 'your_mongodb_host',
        'PORT': your_mongodb_port,
        'USER': 'your_mongodb_username',
        'PASSWORD': 'your_mongodb_password',

Replace the placeholders with your actual MongoDB connection details.

Create Django Models

You can define your Django models as you would normally do with a relational database. The django-mongodb-engine library will handle the conversion of your models to MongoDB documents.

Perform Database Operations

You can use Django’s standard ORM methods and queries to interact with your MongoDB database, just like you would with a relational database.

Create a new record:

from your_app.models import YourModel

obj = YourModel(field1='value1', field2='value2')

To query the database:

queryset = YourModel.objects.filter(field1='value1')

Leave a Reply

Your email address will not be published. Required fields are marked *