### Install Django MongoDB Backend Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/install Installs the 'django-mongodb-backend' package and its required dependencies, including PyMongo and Django, using pip within an activated virtual environment. ```bash pip install django-mongodb-backend ``` -------------------------------- ### Create and Activate Virtual Environment (macOS/Linux) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/install Creates a Python virtual environment named 'venv' and activates it. This isolates project dependencies. Replace 'python' if a different interpreter is needed. ```bash python -m venv venv source venv/bin/activate ``` -------------------------------- ### Start Django Development Server Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/connect-mongodb Runs the Django development server to verify the project setup and MongoDB connection. Access the running application via `http://127.0.0.1:8000/`. ```bash python manage.py runserver ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/install Creates a Python virtual environment named 'venv' and activates it on Windows. This isolates project dependencies. Replace 'python' if a different interpreter is needed. ```bash python -m venv venv . venv\Scripts\activate ``` -------------------------------- ### Start Django Development Server Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-admin This command starts the Django development server, making your application accessible via a web browser. It's typically used for development and testing purposes. Once running, you can access your application at the specified local URL. ```bash python manage.py runserver ``` -------------------------------- ### Create Django Project with MongoDB Template Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/connect-mongodb Creates a new Django project named 'quickstart' using a custom template that includes MongoDB-specific configurations for migrations and primary keys. ```bash django-admin startproject quickstart --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/5.1.x.zip ``` -------------------------------- ### Start Python Shell for Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/write-data This command starts the Python interactive shell within your Django project environment, allowing you to execute Python code that interacts with your Django models and database. ```bash python manage.py shell ``` -------------------------------- ### Start Transaction as Context Manager - Django MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/transactions Starts a database transaction using the `transaction.atomic()` context manager in Django MongoDB Backend. This creates an atomic block where all database operations are guaranteed to be performed as a single unit. Changes are committed upon successful exit from the `with` block or rolled back on exception. ```python from django_mongodb_backend import transaction def insert_movie_transaction(): with transaction.atomic(): Movie.objects.create( title="Poor Things", runtime=141, genres=["Comedy", "Romance"] ) ``` -------------------------------- ### Import Models and Modules for Django MongoDB Shell Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Imports necessary models (`Movie`, `Award`) and modules (`timezone`, `datetime`) for interacting with MongoDB data through the Django shell. This setup is required before running query examples. ```python from .models import Movie, Award from django.utils import timezone from datetime import datetime ``` -------------------------------- ### Configure App URLs Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app Defines URL patterns for the 'sample_mflix' Django app, mapping specific URL paths to the corresponding views. This includes URLs for displaying recent movies, listing viewers, and the application's root index. ```python from django.urls import path from . import views urlpatterns = [ path("recent_movies/", views.recent_movies, name="recent_movies"), path("viewers_list/", views.viewers_list, name="viewers_list"), path("", views.index, name="index"), ] ``` -------------------------------- ### Include App in Django Project Settings Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app This Python code snippet shows how to add the 'sample_mflix' application to your Django project's `INSTALLED_APPS` setting in `settings.py`. This step is crucial for Django to recognize and utilize the application's models, views, and templates. ```python INSTALLED_APPS = [ 'sample_mflix.apps.SampleMflixConfig', 'quickstart.apps.MongoAdminConfig', 'quickstart.apps.MongoAuthConfig', 'quickstart.apps.MongoContentTypesConfig', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ``` -------------------------------- ### Create Django App with MongoDB Template Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app This command creates a new Django application named 'sample_mflix' using a custom template from a specified GitHub URL. This template is pre-configured to work with MongoDB, ensuring necessary settings like 'default_auto_field' are included. ```bash python manage.py startapp sample_mflix --template https://github.com/mongodb-labs/django-mongodb-app/archive/refs/heads/5.1.x.zip ``` -------------------------------- ### Create and Apply Django Database Migrations Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app These bash commands are used to generate database migration files for the 'sample_mflix' app and then apply those migrations to the database. This process ensures that your database schema reflects the changes made to your Django models, such as the addition of 'Movie', 'Award', and 'Viewer' models. ```bash python manage.py makemigrations sample_mflix python manage.py migrate ``` -------------------------------- ### Start Transaction as Decorator - Django MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/transactions Starts a database transaction using the `@transaction.atomic` decorator in Django MongoDB Backend. This ensures that all database operations within the decorated function are atomic. If the function completes successfully, changes are committed; otherwise, they are rolled back. ```python from django_mongodb_backend import transaction @transaction.atomic def insert_movie_transaction(): Movie.objects.create( title="Poor Things", runtime=141, genres=["Comedy", "Romance"] ) ``` -------------------------------- ### Import Models and Utilities for Django MongoDB Shell Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/raw-queries Imports necessary models (`Movie`, `Theater`) and utilities (`timezone`, `datetime`) for interacting with MongoDB from the Django Python interactive shell. These imports are required before running any code examples. ```python from .models import Movie, Theater from django.utils import timezone from datetime import datetime ``` -------------------------------- ### Retrieve One Document in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Retrieves a single document from a MongoDB collection using the `get()` method in Django. This method requires a query filter and raises an error if zero or multiple documents match. The `first()` method can be used to safely retrieve one document from a potentially larger result set. The example retrieves a movie by its title. ```python Movie.objects.get(title="Finding Nemo") ``` -------------------------------- ### Django Views for Displaying Data Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app Implements Django views to handle HTTP requests and render data from the defined MongoDB models. Includes a basic index view, a view to display recent movies, and a view to list viewers, rendering data to specified HTML templates. ```python from django.http import HttpResponse from django.shortcuts import render from .models import Movie, Viewer def index(request): return HttpResponse("Hello, world. You're at the application index.") def recent_movies(request): movies = Movie.objects.order_by("-released")[:5] return render(request, "recent_movies.html", {"movies": movies}) def viewers_list(request): viewers = Viewer.objects.order_by("name")[:10] return render(request, "viewers_list.html", {"viewers": viewers}) ``` -------------------------------- ### Configure Project URLs to Include App URLs Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app Integrates the 'sample_mflix' app's URLs into the main project's URL configuration. This involves including the app's `urls.py` file under the project's root URL path, allowing access to the app's defined views through the main application. ```python from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("sample_mflix.urls")), ] ``` -------------------------------- ### Create Viewers List HTML Template Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app This HTML template displays an alphabetical list of viewers in a table format. It iterates through a 'viewers' list provided by the Django view, showing each viewer's name and email. If no viewers are found, it displays a 'No viewer found' message spanning both columns. ```html Viewers List

Alphabetical Viewers List

{% for viewer in viewers %} {% empty %} {% endfor %}
Name Email
{{ viewer.name }} {{ viewer.email }}
No viewer found.
``` -------------------------------- ### Insert Viewer Object into MongoDB with Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/write-data Creates and inserts a new Viewer document into the MongoDB 'users' collection using the Django ORM. This example shows how to add viewer information such as name and email. ```python viewer = Viewer.objects.create( name="Abigail Carter", email="abigail.carter@fakegmail.com" ) ``` -------------------------------- ### Create Recent Movies HTML Template Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app This HTML template is used to display a list of the five most recent movies. It iterates through a 'movies' list provided by the Django view, formatting each movie's title and release date. If no movies are found, it displays a 'No movies found' message. ```html Recent Movies

Five Most Recent Movies

``` -------------------------------- ### Create Compound Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This example shows how to create a compound index on multiple fields ('title' and 'cook_time') within a Django model. The index is defined in the model's Meta class, specifying the fields to be included in the compound index. ```python class Meta: db_table = "recipes" indexes = [ models.Index(fields=["title", "cook_time"]), ] ``` -------------------------------- ### Create Embedded Document Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This example demonstrates how to create an index on an embedded document field ('nutrition') in a Django model. This index is useful for queries that specify the entire embedded document. ```python class Meta: db_table = "recipes" indexes = [ models.Index(fields=["nutrition"]), ] ``` -------------------------------- ### Read First Matching Document with Django and MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/crud Retrieves the first document that matches the query criteria using Django's filter() followed by first(). This is a safe way to get a single document when multiple matches are possible, avoiding errors from get(). ```python Movie.objects.filter(title="Boyhood").first() ``` -------------------------------- ### Run Raw Database Queries in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Enables running complex MongoDB queries not supported by Django's standard query API using the `raw_aggregate()` method. This method allows passing a MongoDB aggregation pipeline as an argument for custom query execution. Refer to the external guide for detailed instructions. ```python # Example usage would involve defining an aggregation pipeline # See external documentation for specific syntax and examples. ``` -------------------------------- ### Query by Primary Key (ObjectId) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Query a document by its primary key, which is stored as a MongoDB ObjectId. This example retrieves a 'Movie' document using its ObjectId. ```python from bson import ObjectId Movie.objects.get(pk=ObjectId("573a1394f29313caabce0d37")) ``` ```python from bson import ObjectId Movie.objects.get(id=ObjectId("573a1394f29313caabce0d37")) ``` -------------------------------- ### Similarity Search with SearchMoreLikeThis in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search The SearchMoreLikeThis expression finds documents that are similar to one or more provided example documents or query criteria. It leverages the MongoDB moreLikeThis operator for relevance scoring. ```python Movie.objects.annotate(score=SearchMoreLikeThis([ {"title": "The Godfather"}, {"genres": ["Crime", "Drama"]} ])) ``` -------------------------------- ### Retrieve Matching Documents in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Queries a MongoDB collection for documents that match specific criteria using the `filter()` method in Django. This method accepts a query filter to specify conditions, returning a QuerySet of matching documents. An example filters for movies with a runtime of 300. ```python Movie.objects.filter(runtime=300) ``` -------------------------------- ### Execute SearchEquals Query (Python) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search Demonstrates how to use the `SearchEquals` expression to find documents where a specific field matches an exact value. This example queries the `movies` collection for documents with the title 'Finding Nemo'. Requires an index with 'token' type on the 'title' field. ```python Movie.objects.annotate(score=SearchEquals(path="title", value="Finding Nemo")) ``` -------------------------------- ### Python Django Comparison Lookup Example Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Illustrates using the 'lte' (less than or equal to) field lookup in Django with MongoDB to filter documents based on a numerical field. This allows for range-based queries. The general syntax is Model.objects.filter(__=). ```python Movie.objects.filter(runtime__lte=50) ``` -------------------------------- ### Annotate and Filter JSONField with KT Expressions Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Use KT expressions with Django's annotate() method to create new fields based on JSONField data. This example annotates movies with a 'score' based on 'imdb.rating' and then orders them by this score in descending order. ```python from django.db.models.fields.json import KT Movie.objects.annotate(score=KT("imdb__rating")).all().order_by("-score") ``` -------------------------------- ### Create Unique Single Field Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This example demonstrates how to create a unique single field index on the 'cuisine' field of a Django model by setting the 'unique=True' option on the model field. This prevents duplicate values in the 'cuisine' field. ```python cuisine = models.CharField(max_length=200, unique=True) ``` -------------------------------- ### Query with Multiple Criteria using Q Objects in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query This Python code snippet demonstrates how to use Q objects to construct complex queries with multiple matching criteria. It filters Movie documents where the title starts with 'Funny' or 'Laugh' and the genres array does not contain 'Comedy'. This method is useful for building dynamic and intricate search conditions. ```python Movie.objects.filter( (Q(title__startswith="Funny") | Q(title__startswith="Laugh")) & ~Q(genres__contains=["Comedy"]) ) ``` -------------------------------- ### Define GeoDjango Models for Geospatial Data Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/geodjango Define Django models using `django.contrib.gis.db.models` for geospatial fields and `django_mongodb_backend.fields.EmbeddedModelField` for embedded documents. This example shows a `Theater` model with a `Location` embedded model containing a `PointField`. ```python from django.contrib.gis.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelField class Location(EmbeddedModel): address = models.JSONField(null=True) geo = models.PointField() class Theater(models.Model): theater_id = models.IntegerField(default=0, db_column="theaterId") location = EmbeddedModelField(Location, null=True, blank=True) class Meta: db_table = "theaters" managed = False def __str__(self): return self.theater_id ``` -------------------------------- ### Django Models for MongoDB Collections Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-app Defines Django models for 'movies' and 'users' collections in MongoDB, utilizing django-mongodb-backend for embedded documents and arrays. The Movie model includes an EmbeddedModelField for awards and an ArrayField for genres. Managed = False indicates the models do not create or manage database tables directly. ```python from django.db import models from django.conf import settings from django_mongodb_backend.fields import EmbeddedModelField, ArrayField from django_mongodb_backend.models import EmbeddedModel class Award(EmbeddedModel): wins = models.IntegerField(default=0) nominations = models.IntegerField(default=0) text = models.CharField(max_length=100) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) awards = EmbeddedModelField(Award, null=True, blank=True) genres = ArrayField(models.CharField(max_length=100), null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title class Viewer(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=200) class Meta: db_table = "users" managed = False def __str__(self): return self.name ``` -------------------------------- ### Combine Search Expressions with Bitwise Operators in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search This example shows how to combine Atlas Search expressions using bitwise OR (|) operator. It uses `SearchText` and `SearchIn` classes. The `|` operator allows documents to match either the first expression or the second, or both. The result is a Django ORM query annotated with the combined expression's score. ```python expr = SearchText(path="plot", query="heartwarming") | SearchIn(path="genres", value=["Romance", "Comedy"]) Movie.objects.annotate(score=expr) ``` -------------------------------- ### Query JSONField Nested Field Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Query data within a JSONField by chaining field names with double underscores. This example filters movies where the nested 'votes' field within 'imdb' exceeds 900000. ```python Movie.objects.filter(imdb__votes__gt=900000) ``` -------------------------------- ### Sort Query Results by Field in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query This Python example shows how to sort query results in ascending order based on a specified field using the order_by() method. It filters Movie documents by title and then sorts them by the 'released' field. This is useful for presenting data in a structured and predictable manner. ```python Movie.objects.filter(title__startswith="Rocky").order_by("released") ``` -------------------------------- ### Vector Search Query with Relevance Score in Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-vector-search This example extends the basic vector search to include the relevance score for each document. It uses the `values()` method to retrieve the 'title' and 'score' fields, ordering the results by relevance. The output displays a QuerySet of dictionaries containing movie titles and their corresponding scores. ```python vector_values = [float(i % 10) * 0.1 for i in range(1536)] MovieWithEmbeddings.objects.annotate( score=SearchVector( path="plot_embedding", query_vector=vector_values, limit=5, num_candidates=150, exact=False, ) ).values("title", "score") ``` -------------------------------- ### Python Django Text Match Lookup Example Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Demonstrates how to use the 'contains' field lookup in Django with the MongoDB backend to find documents where a field's text value partially matches a given string. This is useful for partial string searches. The syntax follows Model.objects.filter(__=). ```python Movie.objects.filter(plot__contains="coming-of-age") ``` -------------------------------- ### Read Single Document with Django and MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/crud Retrieves a single document from a MongoDB collection that matches the query criteria using Django's get() method. This method is suitable when expecting exactly one result. It raises an error if zero or multiple documents match the query. ```python Movie.objects.get(title="Boyhood") ``` -------------------------------- ### Exclude Matching Documents in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Excludes documents from a MongoDB collection that do not meet specified search criteria using the `exclude()` method in Django. This method takes exclusion criteria as arguments. The example excludes documents released before a specific date using the `lt` field lookup. ```python Movie.objects.exclude(released__lt=timezone.make_aware(datetime(1980, 1, 1))) ``` -------------------------------- ### Handle Transaction Errors in Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/transactions Implement error handling around Django's atomic code blocks to manage exceptions during transactions. If a transaction fails, Django might not roll back changes, necessitating manual restoration of original field values to maintain data consistency. This example reverts a title change if the save operation fails. ```python from django.db import transaction, DatabaseError # Assume Movie model is defined elsewhere movie = Movie.objects.get(title="Jurassic Park") movie.title = "Jurassic Park I" try: with transaction.atomic(): movie.save() except DatabaseError: movie.title = "Jurassic Park" # Revert title change on error if movie.title == "Jurassic Park I": movie.plot = "An industrialist invites experts to visit his theme park of cloned dinosaurs. After a power failure," \ " the creatures run loose, putting everyone's lives, including his grandchildren's, in danger." movie.save() ``` -------------------------------- ### Create Django Admin User Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-admin This command-line utility creates a superuser account for accessing the Django admin site. It prompts for username, email, and password to set up the administrator credentials. Ensure you are in your project's root directory before running. ```bash python manage.py createsuperuser ``` ```bash Username: admin Email address: admin@example.com Password: Password (again): ``` -------------------------------- ### Run Django Database Migrations for MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/models These bash commands are used to manage database migrations for your Django project when using MongoDB. `makemigrations` creates migration files for your application, and `migrate` applies those migrations to create or update collections. ```bash python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Define Django Recipe Model with MongoDB Backend Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This Python code defines the `Nutrition` and `Recipe` models. The `Recipe` model is configured to map to a MongoDB collection named 'recipes' using `django_mongodb_backend`. ```python from django.db import models from django.db.models import Q, F from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelField, ArrayField class Nutrition(EmbeddedModel): calories = models.IntegerField(default=0) carb_grams = models.IntegerField(default=0) protein_grams = models.IntegerField(default=0) class Recipe(models.Model): title = models.CharField(max_length=200) cuisine = models.CharField(max_length=200) cook_time = models.IntegerField(default=0) allergens = ArrayField(models.CharField(max_length=100), null=True, blank=True) nutrition = EmbeddedModelField(Nutrition, null=True, blank=True) class Meta: db_table = "recipes" def __str__(self): return self.title ``` -------------------------------- ### Add Application to Django Settings Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/models This Python code snippet shows how to add your Django application module to the INSTALLED_APPS list in your project's settings.py file. This step is necessary for Django to recognize and use your defined models. ```python INSTALLED_APPS = [ '', # Include other app modules here ] ``` -------------------------------- ### Run Atlas Search Phrase Query with Highlight - Python Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/raw-queries Executes an Atlas Search query using the `$search` aggregation stage to find documents matching a specific phrase with a given slop. It also utilizes the `$project` stage with `$meta: 'searchHighlights'` to return highlighted portions of the matched text. This requires an existing Atlas Search index covering the specified field. ```python movies = Movie.objects.raw_aggregate([ { "$search": { "index": "", "phrase": { "path": "plot", "query": "whirlwind romance", "slop": 3 }, "highlight": { "path": "plot" } } }, { "$project": { "title": 1, "highlight": {"$meta": "searchHighlights"} } } ]) for m in movies: print(f"Title: {m.title}, text match details: {m.highlight}\n") ``` -------------------------------- ### Exit Python Shell Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/write-data Exits the current Python interactive shell session. ```python exit() ``` -------------------------------- ### Automatically Configure MongoDB Connection in Django (Python) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/connect This snippet demonstrates how to use the `parse_uri()` function to automatically configure the `DATABASES` setting for a MongoDB connection in Django. It requires the `django_mongodb_backend` library and takes a MongoDB connection URI and database name as input. ```python import django_mongodb_backend MONGODB_URI = "mongodb+srv://my_user:my_password@cluster0.example.mongodb.net/?retryWrites=true&w=majority" DATABASES["default"] = django_mongodb_backend.parse_uri(MONGODB_URI, db_name="") ``` -------------------------------- ### Register Django Model with Admin Site Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/create-admin This Python code snippet registers a Django model ('Viewer') with the Django admin site. This allows instances of the 'Viewer' model to be managed (viewed, created, edited, deleted) through the admin interface. It requires importing the 'admin' module and the model itself. ```python from django.contrib import admin from .models import Viewer admin.site.register(Viewer) ``` -------------------------------- ### Import Models and Modules in Python Shell Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-vector-search Imports the necessary `MovieWithEmbeddings` model from your Django application's models and prepares the Python interactive shell environment for database interactions. ```python from .models import MovieWithEmbeddings ``` -------------------------------- ### Create Partial Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This snippet shows how to create a partial index on the 'cuisine' field, which only indexes documents where 'cook_time' is less than 30. Partial indexes are created using the 'condition' argument with a Q object. ```python class Meta: db_table = "recipes" indexes = [ models.Index(fields=["cuisine"], condition=Q(cook_time__lt=30), name="fast_cuisine_idx"), ] ``` -------------------------------- ### Configure Django Database Settings for MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/connect-mongodb Updates the `DATABASES` setting in Django's `settings.py` file to use the `django-mongodb-backend` for connecting to a MongoDB deployment. Requires a connection string URI and optionally a database name. ```python DATABASES = { "default": django_mongodb_backend.parse_uri("", db_name=""), } ``` -------------------------------- ### Create MongoDB Indexes in Django Meta Class Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This Python code snippet demonstrates how to define MongoDB indexes for a Django model by specifying the `indexes` option within the model's `Meta` class. It shows the basic structure for adding one or more `models.Index` definitions. ```python class Meta: indexes = [ models.Index(), models.Index(), # add more indexes here ] ``` -------------------------------- ### Manually Configure Django Database Settings for MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/connect Manually configure your Django project's connection to MongoDB by updating the DATABASES variable in your settings.py file. This method requires specifying engine, host, name, user, password, port, and optional connection options. ```python DATABASES = { "default": { "ENGINE": "django_mongodb_backend", "HOST": "mongodb+srv://cluster0.example.mongodb.net", "NAME": "my_database", "USER": "my_user", "PASSWORD": "my_password", "PORT": 27017, "OPTIONS": { "retryWrites": "true", "w": "majority", }, }, } ``` -------------------------------- ### Filter and Project Document Fields using raw_aggregate() Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/raw-queries This snippet demonstrates how to use the `raw_aggregate()` method on a Django MongoDB Backend model manager to filter documents by title and project specific fields. It takes an aggregation pipeline as input, consisting of `$match` and `$project` stages. The method returns deferred model instances, allowing for on-demand loading of additional fields. ```python movies = Movie.objects.raw_aggregate([ {" $match": {"title": "The Parent Trap"}}, {" $project": { "title": 1, "released": 1 } }]) for m in movies: print(f"Plot of {m.title}, released on {m.released}: {m.plot}\n") ``` -------------------------------- ### Expose MongoClient in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/raw-queries This code snippet shows how to access the underlying MongoClient object from Django's database connections. This allows direct use of PyMongo driver methods, such as create_index(), which are not available through the Django ORM or raw_aggregate(). Replace '' with your specific database configuration key. ```python from django.db import connections client = connections[""].database.client ``` -------------------------------- ### Run Atlas Search Query Syntax (Python) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search Illustrates the basic syntax for running an Atlas Search query using Django's `annotate()` method. It involves specifying a score argument with a search operator and field path. ```python Model.objects.annotate( score=(path=") ) ``` -------------------------------- ### Query Movies Collection by Runtime in Django/Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/query-data This snippet demonstrates querying the 'movies' collection in MongoDB via Django models. It filters movies based on a runtime value less than a specified number (10) using the `filter()` method with a less-than lookup (`__lt`). ```python Movie.objects.filter(runtime__lt=10) ``` -------------------------------- ### Configure GeoDjango in Django Settings Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/geodjango Add `django.contrib.gis` to the `INSTALLED_APPS` setting in your `settings.py` file to enable GeoDjango support. This is a prerequisite for using geospatial data features. ```python INSTALLED_APPS = [ "django.contrib.gis", # ... Other installed apps ] ``` -------------------------------- ### Boost Relevance Score with SearchScoreOption in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search This snippet illustrates how to customize relevance scores using the `SearchScoreOption` class. It specifically shows how to boost the score of documents matching a `SearchEquals` expression by a factor of 3. This involves creating a `SearchScoreOption` with a 'boost' configuration and applying it to the `score` argument of the `SearchEquals` expression within a Django ORM query. ```python boost = SearchScoreOption({"boost": {"value": 3}}) Movie.objects.annotate( score=SearchEquals( path="title", value="Life of Pi", score=boost ) ) ``` -------------------------------- ### Define Django MongoDB Models Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/raw-queries Defines `Movie` and `Theater` models for use with Django MongoDB Backend. These models utilize `MongoManager` for MongoDB-specific operations and include inner `Meta` classes for database configuration and `__str__()` methods for string representation. ```python from django.db import models from django_mongodb_backend.fields import ArrayField from django_mongodb_backend.managers import MongoManager class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) genres = ArrayField(models.CharField(max_length=100), null=True, blank=True) objects = MongoManager() class Meta: db_table = "movies" managed = False def __str__(self): return self.title class Theater(models.Model): theaterId = models.IntegerField(default=0) objects = MongoManager() class Meta: db_table = "theaters" managed = False def __str__(self): return self.theaterId ``` -------------------------------- ### Insert Document into MongoDB using Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/crud Demonstrates how to insert a new document into a MongoDB collection using Django MongoDB Backend. It shows two methods: using the `create()` method on the model manager for a single-step creation and saving, and creating a model instance first followed by calling the `save()` method. ```python Movie.objects.create(title="Poor Things", runtime=141) ``` ```python movie = Movie(title="Poor Things", runtime=141) movie.save() ``` -------------------------------- ### Import Django and Datetime Modules Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/write-data Imports necessary classes and modules from Django and the Python datetime library. These are required for working with models (Movie, Award, Viewer) and handling date/time objects, specifically for making timezone-aware datetimes. ```python from sample_mflix.models import Movie, Award, Viewer from django.utils import timezone from datetime import datetime ``` -------------------------------- ### Query Users Collection by Email in Django/Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/query-data This snippet shows how to query the 'users' collection in MongoDB using Django models to find a user by their email address. It imports the necessary Viewer model and uses the `filter().first()` method to retrieve a single matching record. ```python from sample_mflix.models import Movie, Viewer Viewer.objects.filter(email="jason_momoa@gameofthron.es").first() ``` -------------------------------- ### Import Models and Search Expressions (Python) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search Imports necessary models (`Movie`, `Theater`) and Atlas Search expression classes from `django_mongodb_backend.expressions`. These are required for running Atlas Search queries within the Django shell. ```python from .models import Movie, Theater from django_mongodb_backend.expressions import ( SearchEquals, SearchAutocomplete, SearchExists, SearchIn, SearchPhrase, SearchQueryString, SearchRange, SearchRegex, SearchText, SearchWildcard, SearchGeoShape, SearchGeoWithin, SearchMoreLikeThis, CompoundExpression, SearchScoreOption ) ``` -------------------------------- ### Define Movie Model - Django MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/transactions Defines the `Movie` model for interacting with the `sample_mflix.movies` collection in MongoDB. It includes fields for title, plot, runtime, release date, and genres. The `Meta` class specifies the database table and that the model is not managed by Django's migrations. ```python from django.db import models from django_mongodb_backend.fields import ArrayField class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) genres = ArrayField(models.CharField(max_length=100), null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title ``` -------------------------------- ### Retrieve First Document from Query Set in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Retrieves the first document matching the specified filter criteria from a MongoDB collection using Django's ORM. This is useful when you only need a single record and want to optimize query performance. It chains the `first()` method after `filter()`. ```python Movie.objects.filter(genres=["Crime", "Comedy"]).first() ``` -------------------------------- ### Skip and Limit Query Results using Slicing in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query This Python snippet illustrates how to retrieve a specific subset of query results using array slicing. It filters Movie documents by the 'released' date and then returns the third and fourth results (index 2 to 4). This technique is essential for pagination and controlling data retrieval volume. ```python Movie.objects.filter(released=timezone.make_aware(datetime(2010, 7, 16)))[2:4] ``` -------------------------------- ### Perform Atlas Vector Search Query with Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-vector-search Demonstrates how to construct and execute an Atlas Vector Search query using Django MongoDB Backend's `SearchVector` expression. This allows for semantic searching based on vector similarity, with options for filtering and controlling the search parameters. ```python from django_mongodb_backend.expressions import SearchVector Model.objects.annotate( score=SearchVector( path="", query_vector=[], limit=, num_candidates=, exact=, filter= ) ) ``` -------------------------------- ### Retrieve All Documents in Python (Django) Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Retrieves all documents from a MongoDB collection using the `all()` method on the model's manager in Django. This method returns a QuerySet containing all documents in the specified collection. No specific inputs are required beyond the model definition. ```python Movie.objects.all() ``` -------------------------------- ### Define a Django Model for MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/models This Python code defines a basic Django model class that can be mapped to a MongoDB collection. It includes field definitions, an inner Meta class for model options like database table name and management, and a __str__() method for string representation. ```python from django.db import models class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title ``` -------------------------------- ### Wildcard Search with SearchWildcard in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search The SearchWildcard expression allows for flexible string matching using wildcard characters like '*' and '?'. It searches a specified field against a query pattern. This is useful for partial string matches. ```python Movie.objects.annotate(score=SearchWildcard(path="title", query="Star*")) ``` -------------------------------- ### Perform full-text search with fuzzy matching using SearchText Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search The SearchText operator performs full-text searches on string fields, supporting fuzzy matching and configurable criteria. It requires a 'path' and a 'query' term. Optional parameters include 'fuzzy' for edit distance, 'match_criteria' (all/any), 'synonyms', and 'score'. This is suited for user-facing search functionalities. ```python Movie.objects.annotate(score=SearchText( path="plot", query="sudden disappearance", fuzzy={"maxEdits": 2}, match_criteria="all" )) ``` -------------------------------- ### Create Multikey Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This snippet illustrates the creation of a multikey index on an array field ('allergens') in a Django model. MongoDB automatically handles array fields as multikey indexes when an index is defined on them. ```python class Meta: db_table = "recipes" indexes = [ models.Index(fields=["allergens"], name="allergy_idx"), ] ``` -------------------------------- ### Basic Vector Search Query in Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-vector-search This code snippet demonstrates a basic vector search query on the `sample_mflix.embedded_movies` collection. It queries the `plot_embedding` field, limits results to 5 documents, and uses Approximate Nearest Neighbor (ANN) search with 150 candidates. The output shows the retrieved movie objects. ```python vector_values = [float(i % 10) * 0.1 for i in range(1536)] MovieWithEmbeddings.objects.annotate( score=SearchVector( path="plot_embedding", query_vector=vector_values, limit=5, num_candidates=150, exact=False, ) ) ``` -------------------------------- ### Combine Search Expressions with CompoundExpression in Python Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search This snippet demonstrates using the CompoundExpression class to combine multiple Atlas Search criteria. It requires the `CompoundExpression`, `SearchExists`, `SearchText`, and `SearchIn` classes. The `must` argument specifies mandatory conditions, while `must_not` excludes documents matching certain criteria. This results in a Django ORM query annotated with a relevance score. ```python plot_exists = SearchExists(path="plot") plot_text = SearchText(path="plot", query="fast-paced") genres_range = SearchIn(path="genres", value=["Romance", "Comedy"]) Movie.objects.annotate( score=CompoundExpression( must=[plot_exists, plot_text], must_not=[genres_range] ) ) ``` -------------------------------- ### Define Django Model with Embeddings for MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-vector-search Defines a Django model `MovieWithEmbeddings` that maps to the `sample_mflix.embedded_movies` collection in MongoDB. It includes a `CharField` for the title, an `IntegerField` for runtime, and an `ArrayField` for the plot embeddings, suitable for vector search. ```python from django.db import models from django_mongodb_backend.fields import ArrayField class MovieWithEmbeddings(models.Model): title = models.CharField(max_length=200) runtime = models.IntegerField(default=0) plot_embedding = ArrayField(models.FloatField(), size=1536, null=True, blank=True) class Meta: db_table = "embedded_movies" managed = False def __str__(self): return self.title ``` -------------------------------- ### Create Compound Unique Index in Django Meta Class Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This Python code snippet defines the Meta class for a Django model, specifying a unique compound index on the 'title' and 'cuisine' fields using `models.UniqueConstraint`. This automatically creates an index in the database to enforce the uniqueness of combined 'title' and 'cuisine' values. ```python class Meta: db_table = "recipes" constraints = [ models.UniqueConstraint(fields=["title", "cuisine"], name="unique_regional_meal"), ] ``` -------------------------------- ### Create Single Field Index in Django Model Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/model-data/indexes This snippet demonstrates how to create a single field index on the 'title' field of a Django model. This is achieved by defining an index in the model's Meta class. Alternatively, the db_index=True option can be set directly on the model field. ```python class Meta: db_table = "recipes" indexes = [ models.Index(fields=["title"], name="title_idx"), ] ``` ```python class Recipe(models.Model): title = models.CharField(max_length=200, db_index=True) ``` -------------------------------- ### Perform Lucene-style text search with SearchQueryString Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search The SearchQueryString operator enables text, wildcard, regex, fuzzy, and range searches on string fields using Lucene-style queries. It requires a 'path' for the field and a 'query' string. An optional 'score' can be provided. This is useful for complex text searching within your Django application. ```python Movie.objects.annotate(score=SearchQueryString(path="plot", query="romance AND (paris OR tokyo)")) ``` -------------------------------- ### Define Movie and Award Models for Django MongoDB Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query Defines the `Award` and `Movie` models using Django's ORM, tailored for use with the Django MongoDB Backend. The `Movie` model includes fields for title, plot, runtime, release date, awards (as an embedded model), genres (as an array), and IMDb data (as JSON). ```python from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelField, ArrayField class Award(EmbeddedModel): wins = models.IntegerField(default=0) nominations = models.IntegerField(default=0) text = models.CharField(max_length=100) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) awards = EmbeddedModelField(Award) genres = ArrayField(models.CharField(max_length=100), null=True, blank=True) imdb = models.JSONField(null=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title ``` -------------------------------- ### Phrase Matching Search with SearchPhrase in Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/interact-data/atlas-search The SearchPhrase expression matches exact or near-exact sequences of terms within a field. It requires the field name and the phrase query. Optional parameters include 'slop' for word distance, 'synonyms' for synonym mappings, and 'score' for relevance configuration. ```python Movie.objects.annotate(score=SearchPhrase(path="plot", query="space adventure", slop=2)) ``` -------------------------------- ### Insert Movie Object into MongoDB with Django Source: https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/write-data Creates and inserts a new Movie document into the MongoDB database using the Django ORM. It demonstrates how to create related objects (Award) and set various fields including title, plot, runtime, release date, awards, and genres. ```python movie_awards = Award(wins=122, nominations=245, text="Won 1 Oscar") movie = Movie.objects.create( title="Minari", plot="A Korean-American family moves to an Arkansas farm in search of their own American Dream", runtime=217, released=timezone.make_aware(datetime(2020, 1, 26)), awards=movie_awards, genres=["Drama", "Comedy"] ) ```