Docs Menu
Docs Home
/
Django MongoDB Backend
/

Write Data to MongoDB

You can use your application's models to update documents stored in the sample_mflix database. To update documents, enter the Python interactive shell and call create, update, and delete functions on your model objects.

1

From your project's root directory, run the following command to enter the Python shell:

python manage.py shell
2

From your Python shell, run the following code to import your models and the module for creating a datetime object:

from sample_mflix.models import Movie, Award, Viewer
from django.utils import timezone
from datetime import datetime
3

Run the following code to create an Movie object that stores data about a movie titled "Minari", including its awards in an Award object:

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"]
)
4

The Movie object created in the previous step has inaccurate data: the runtime value is 217, but the correct runtime value is 117.

Run the following code to update the object's runtime value:

movie.runtime = 117
movie.save()
5

You can also use your Viewer model to insert documents into the sample_mflix.users collection. Run the following code to create a Viewer object that stores data about a movie viewer named "Abigail Carter":

viewer = Viewer.objects.create(
name="Abigail Carter",
email="abigail.carter@fakegmail.com"
)
6

One movie viewer named "Alliser Thorne" no longer uses the movie streaming site. To remove this viewer's corresponding document from the database, run the following code:

old_viewer = Viewer.objects.filter(name="Alliser Thorne").first()
old_viewer.delete()
7

Exit the Python shell by running the following code:

exit()

Then, start your server by running the following command from your project's root directory:

python manage.py runserver
8

To ensure that you inserted a Movie object into the database, visit the http://127.0.0.1:8000/recent_movies/ URL. You can see a list of five movies in the sample_mflix.movies database, with your new movie listed at the top.

Then, ensure that you inserted a Viewer object into the database by visiting the http://127.0.0.1:8000/viewers_list/ URL. You can see a list of ten viewer names in the sample_mflix.users database, with your new viewer listed at the top. Ensure that the viewer named "Alliser Thorne", deleted in a previous step, does not appear in this list.

After completing these steps, you have inserted and edited documents in the sample_mflix sample database.

Back

Create an Application