Perform CRUD Operations
On this page
Overview
In this guide, you can learn how to use Django MongoDB Backend to run create, read, update, and delete (CRUD) operations on your MongoDB collection.
You can also use the Django admin site to edit your models and their corresponding collections on a web interface. For more information, see the Django Admin Site entry in the Django documentation.
Query API
You can use methods provided by the Django QuerySet
API to run
CRUD operations. To run these operations, you can call QuerySet
methods
on your model's manager. The Manager
class handles database
operations and allows you to interact with your MongoDB data by referencing
Django models. By default, Django adds a Manager
named objects
to every model class.
Tip
To learn more about Django's QuerySet
API, see
QuerySet
in the Django
documentation.
This guide shows how to use the following QuerySet
methods:
create(): Inserts documents into the collection
filter() and get(): Retrieves one or multiple collection documents
update(): Modifies collection documents
delete(): Deletes collection documents
Sample Data
The examples in this guide use the Movie
model, which represents
the sample_mflix.movies
collection from the Atlas sample datasets.
The Movie
model class has the following definition:
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
The Movie
model includes an inner Meta
class, which specifies
model metadata, and a __str__()
method, which defines the
model's string representation. To learn about these
model features, see Define a Model in the
Create Models guide.
Run Code Examples
You can use the Python interactive shell to run the code examples. To enter the shell, run the following command from your project's root directory:
python manage.py shell
After entering the Python shell, ensure that you import the following models and modules:
from <your application name>.models import Movie from django.utils import timezone from datetime import datetime
To learn how to create a Django application that uses the Movie
model and the Python interactive shell to interact with MongoDB documents,
visit the Get Started with Django MongoDB Backend tutorial.
Insert Documents
To insert a document into a collection, call the create()
method on your
model's manager. Pass the new document's field names and field values
as arguments to the create()
method.
Example
The following example calls the create()
method to insert a document
into the sample_mflix.movies
collection. The new document has
a title
value of "Poor Things"
and a runtime
value
of 141
:
Movie.objects.create(title="Poor Things", runtime=141)
The create()
method allows you to create a new Movie
object
and save the object to MongoDB in one method call. Alternatively, you
can create a Movie
object and call save()
, as shown in the following
code:
movie = Movie(title="Poor Things", runtime=141) movie.save()
Tip
To learn more about the create()
method, see
create
in the Django
documentation.
Read Documents
To retrieve documents from your collection, call the filter()
method
on your model's manager. Pass a query filter, or criteria that specifies
which documents to retrieve, as an argument to the filter()
method.
Alternatively, you can call the get()
method to retrieve a single document
that matches your query.
Return Multiple Documents Example
The following example calls the filter()
method to retrieve
documents from the sample_mflix.movies
collection. The query
returns Movie
objects that represent movies released on January 1, 2000:
Movie.objects.filter(released=timezone.make_aware(datetime(2000, 1, 1)))
<QuerySet [<Movie: The Bumblebee Flies Anyway>, <Movie: Angels of the Universe>, <Movie: First Person Plural>, <Movie: Just, Melvin: Just Evil>, <Movie: Sound and Fury>, <Movie: Peppermint Candy>]>
Tip
To learn more about the filter()
method, see
filter
in the Django documentation.
Return One Document Example
To retrieve only one document that matches your query criteria, call the
get()
method and pass a query filter as an argument. The following example
retrieves a document in which the title
value is "Boyhood"
:
Movie.objects.get(title="Boyhood")
<Movie: Boyhood>
Important
If your query matches no documents or multiple documents, the get()
method generates an error. To retrieve one document from a query
that might match multiple, chain the first()
method to filter()
,
as shown in the following code:
Movie.objects.filter(title="Boyhood").first()
Tip
To learn more about the get()
method, see
get
in the Django documentation.
Modify Documents
To modify documents in a collection, call the filter()
and update()
methods on your model's manager. Pass a query filter, or criteria that
specifies which documents to update, as an argument to the filter()
method. Then, pass the fields and values you want to update as
arguments to the update()
method.
Example
The following example calls the update()
method to modify
documents in the sample_mflix.movies
collection. The code matches
a document that has a title
value of "High Fidelity"
and adds a
plot
field:
Movie.objects.filter( title="High Fidelity").update( plot="Rob, a record store owner, recounts his top five breakups,including the one in progress.")
// Outputs the number of modified documents 1
Tip
To learn more about the update()
method, see
update
in the Django documentation.
Delete Documents
To delete documents in a collection, call the filter()
and delete()
methods on your model's manager, Pass a query filter, or criteria
that specifies which documents to delete, as an argument to the
filter()
method.
Example
The following example calls the delete()
method to delete documents
in the sample_mflix.movies
collection. The code matches
and deletes documents that have a runtime
value of 5
:
Movie.objects.filter(runtime=5).delete()
// Outputs the number of deleted documents and objects (16, {'sample_mflix.Movie': 16})
Tip
To learn more about the delete()
method, see
delete
in the Django documentation.
Additional Information
To learn more about performing read operations, see the Specify a Query guide.
To view more create, read, update, and delete examples, see the following steps of the Get Started with Django MongoDB Backend tutorial: