문서 삽입

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