MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Introduction to MongoDB in Python

Lihat Kursus

Petunjuk latihan

  • 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.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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)
Edit dan Jalankan Kode