การแทรกเอกสาร

MongoDB เบื้องต้นใน Python

Filip Schouwenaars

Machine Learning Researcher

ทำไมต้องแทรกข้อมูล?

  • ข้อมูลต้องอยู่ในฐานข้อมูลของคุณ
  • จำเป็นต้องมีวิธีเพิ่มข้อมูล!
  • มีสองวิธี
    • insert_one(): เพิ่มเอกสารทีละรายการ
    • insert_many(): เพิ่มเอกสารหลายรายการพร้อมกัน
MongoDB เบื้องต้นใน Python

การแทรกเอกสารทีละรายการ

from pymongo import MongoClient
client = MongoClient()
mov = client.film.movies

mov.count_documents({})
41
new_movie = {
    "title": "oppenheimer",
    "genre": ["drama", "history"],
    "release_year": 2023,
    "rating": 8.7
}
result = mov.insert_one(new_movie)

ระบบสร้าง _id ที่ไม่ซ้ำกันให้อัตโนมัติ!

result.inserted_id
ObjectId('6837575d10d855c9f6698341')
mov.count_documents({})
42
MongoDB เบื้องต้นใน Python

การแทรกเอกสารหลายรายการ

new_movies = [
    {
        "title": "the holdovers",
        "genre": ["comedy", "drama"],
        "release_year": 2023,
        "rating": 7.9
    },
    {
        "title": "past lives",
        "genre": ["drama", "romance"],
        "release_year": 2023,
        "rating": 7.8
    }
]
result = mov.insert_many(new_movies)
print(result.inserted_ids)
[ObjectId("662ecfe2e89c44eb19ae1234"),
 ObjectId("662ecfe2e89c44eb19ae1235")]

ระบบสร้าง _id ทั้งหมดให้อัตโนมัติ

MongoDB เบื้องต้นใน Python

มาฝึกกันเถอะ!

MongoDB เบื้องต้นใน Python

Preparing Video For Download...