CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Introduction to MongoDB in Python

Afficher le cours

Instructions

  • Create a variable mov that holds the movies collection instance in the film database.
  • Fetch all movies in the collection and store it in all_movies as a Python list.
  • Fetch all movies in the collection that have a release_year equal to 2008 as a Python list.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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)
Modifier et exécuter le code