ドキュメントの挿入

Pythonで学ぶMongoDB入門

Filip Schouwenaars

Machine Learning Researcher

なぜデータを挿入するのか

  • データはデータベース内に必要です
  • 追加する方法が要ります
  • 方法は2つ
    • insert_one(): 1件を追加
    • 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...