Chèn tài liệu

Nhập môn MongoDB với Python

Filip Schouwenaars

Machine Learning Researcher

Vì sao chèn dữ liệu?

  • Dữ liệu phải có trong cơ sở dữ liệu
  • Cần cách để thêm!
  • Hai phương thức
    • insert_one(): thêm 1 tài liệu
    • insert_many(): thêm danh sách tài liệu
Nhập môn MongoDB với Python

Chèn 1 tài liệu

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 duy nhất được tạo tự động!

result.inserted_id
ObjectId('6837575d10d855c9f6698341')
mov.count_documents({})
42
Nhập môn MongoDB với Python

Chèn nhiều tài liệu

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")]

Tất cả _id đều được tạo tự động.

Nhập môn MongoDB với Python

Hãy thực hành!

Nhập môn MongoDB với Python

Preparing Video For Download...