Retrieving documents using .find()
One common way of retrieving documents from a MongoDB collection is .find(). When called on a collection, it will return a cursor object pointing to all records or all records that match a specified filter query. Using list() you can actually fetch the documents, and go from a cursor object to a Python list.
This exercise is part of the course
Introduction to MongoDB in Python
Exercise instructions
- Create a variable
movthat holds themoviescollection instance in thefilmdatabase. - Fetch all movies in the collection and store it in
all_moviesas a Python list. - Fetch all movies in the collection that have a
release_yearequal to 2008 as a Python list.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
from pymongo import MongoClient
client = MongoClient()
# Create mov
mov = ____
# Fetch all movies in the collection
all_movies = ____
print(f"Retrieved {len(all_movies)} movies")
print(all_movies)
# Fetch all movies that have a release year of 2008
some_movies = ____
print(f"Retrieved {len(some_movies)} movies:")
print(some_movies)