插入文件

Python 中的 MongoDB 入門

Filip Schouwenaars

Machine Learning Researcher

為何要插入資料?

  • 資料必須存在於你的資料庫中
  • 需要能加入資料!
  • 兩種方法
    • insert_one(): 新增單一文件
    • insert_many(): 新增文件清單
Python 中的 MongoDB 入門

插入單一文件

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
Python 中的 MongoDB 入門

插入多筆文件

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 都會自動產生。

Python 中的 MongoDB 入門

一起來練習吧!

Python 中的 MongoDB 入門

Preparing Video For Download...