ดึงเอกสารด้วย .find()
วิธีทั่วไปในการดึงเอกสารจาก MongoDB collection คือการใช้ .find() เมื่อเรียกใช้กับ collection จะได้รับออบเจกต์ cursor ที่ชี้ไปยังเรคอร์ดทั้งหมด หรือเรคอร์ดที่ตรงกับเงื่อนไขการกรองที่กำหนด จากนั้นใช้ list() เพื่อดึงเอกสารออกมาจริง ๆ และแปลงจาก cursor object เป็น Python list
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
MongoDB เบื้องต้นใน Python
คำแนะนำการฝึกหัด
- สร้างตัวแปร
movที่เก็บ instance ของ collectionmoviesในฐานข้อมูลfilm - ดึงภาพยนตร์ทั้งหมดใน collection และเก็บไว้ใน
all_moviesในรูปแบบ Python list - ดึงภาพยนตร์ทั้งหมดใน collection ที่มี
release_yearเท่ากับ 2008 ในรูปแบบ Python list
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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)