插入文档

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