문서 삽입
이 페이지의 내용
개요
이 가이드에서는 PyMongo를 사용하여 삽입 작업을 수행하여 MongoDB 컬렉션에 문서를 추가하는 방법을 배울 수 있습니다.
삽입 작업은 하나 이상의 문서를 MongoDB 컬렉션에 삽입하는 작업입니다. insert_one()
또는 insert_many()
메서드를 사용하여 삽입 작업을 수행할 수 있습니다.
참고
_id 필드는 고유해야 합니다.
MongoDB 컬렉션 에서 각 문서 에는 고유한 값을 가진 _id
필드 포함되어야 합니다.
_id
필드 에 값을 지정하는 경우 해당 값이 컬렉션 전체에서 고유한지 확인해야 합니다. 값을 지정하지 않으면 운전자 필드 에 대해 고유한 ObjectId
값을 자동으로 생성합니다.
고유성을 보장하기 위해 운전자 _id
값을 자동으로 생성하도록 하는 것이 좋습니다. 중복된 _id
값은 고유 인덱스 제약 조건을 위반하여 운전자 오류를 반환합니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트 의
sample_restaurants.restaurants
컬렉션 을 사용합니다. 무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 PyMongo 시작하기 튜토리얼을 참조하세요.
문서 하나 삽입
MongoDB 컬렉션에 단일 문서를 추가하려면 insert_one()
메서드를 호출하고 추가하려는 문서를 전달합니다.
다음 예시에서는 restaurants
컬렉션에 문서를 삽입합니다.
sample_restaurants.restaurants.insert_one({"name" : "Mongo's Burgers"})
사용자 지정 클래스의 인스턴스 insert_one()
메서드에 전달할 수도 있습니다. 이는 유형 검사 도구를 사용하는 경우 추가 유형 안전성을 제공합니다. 전달하는 인스턴스 TypedDict
클래스에서 상속되어야 합니다.
참고
Python 3.7 및 이전 버전의 TypedDict
다음 예시 유형 안전성을 추가하기 위해 Restaurant
클래스의 인스턴스 insert_one()
메서드에 전달합니다.
class Restaurant(TypedDict): name: str sample_restaurants.restaurants.insert_one(Restaurant(name="Mongo's Burgers")
여러 문서를 삽입합니다.
MongoDB 컬렉션에 여러 문서를 추가하려면 insert_many()
메서드를 호출하고 추가하려는 문서 목록을 전달합니다.
다음 예에서는 restaurants
컬렉션에 문서 목록을 삽입합니다.
document_list = [ { "name" : "Mongo's Burgers" }, { "name" : "Mongo's Pizza" } ] sample_restaurants.restaurants.insert_many(document_list)
사용자 지정 클래스의 인스턴스 목록을 insert_many()
메서드에 전달할 수도 있습니다. 이는 유형 검사 도구를 사용하는 경우 추가 유형 안전성을 제공합니다. 전달하는 인스턴스는 TypedDict
클래스에서 상속되어야 합니다.
참고
Python 3.7 및 이전 버전의 TypedDict
다음 예시 insert_many()
메서드를 호출하고 Restaurant
클래스의 인스턴스가 포함된 목록을 전달합니다. 이렇게 하면 삽입 작업에 유형 안전성이 추가됩니다.
class Restaurant(TypedDict): name: str document_list = [ Restaurant(name="Mongo's Burgers"), Restaurant(name="Mongo's Pizza") ] sample_restaurants.restaurants.insert_many(document_list)
삽입 동작 수정
insert_one()
메서드는 삽입 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 추가 매개 변수를 선택적으로 허용합니다. 추가 매개변수를 지정하지 않으면 드라이버는 삽입을 사용자 지정하지 않습니다.
속성 | 설명 |
---|---|
| If set to True , allows the write to opt out of
document-level validation.기본값은 False 입니다. |
| ClientSession 의 인스턴스입니다. |
| A comment to attach to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual for more information. |
insert_many()
메서드는 앞의 선택적 매개변수와 선택적 ordered
속성을 허용합니다.
속성 | 설명 |
---|---|
| If set to True , the driver sends documents to the
server in the order provided. If an error occurs, the driver
and server cancel all remaining insert operations.기본값은 True 입니다. |
예시
다음 코드에서는 insert_many()
메서드를 사용하여 컬렉션에 세 개의 새 문서를 삽입합니다. 두 번째 메서드 인수가 bypass_document_validation = True
이므로 이 삽입 작업은 문서 수준 유효성 검사를 우회합니다.
document_list = [ { "name" : "Mongo's Burgers" }, { "name" : "Mongo's Pizza" }, { "name" : "Mongo's Tacos" } ] sample_restaurants.restaurants.insert_many(document_list, bypass_document_validation = True)
문제 해결
클라이언트 유형 주석
MongoClient
객체 에 대한 유형 주석을 추가하지 않으면 유형 검사기에 다음과 유사한 오류가 표시될 수 있습니다.
from pymongo import MongoClient client = MongoClient() # error: Need type annotation for "client"
해결책은 MongoClient
객체 에 client: MongoClient
또는 client: MongoClient[Dict[str, Any]]
로 주석을 추가하는 것입니다.
호환되지 않는 유형
유형 힌트로 MongoClient
를 지정했지만 문서, 키 및 값에 대한 데이터 유형을 포함하지 않는 경우 유형 검사기에 다음과 유사한 오류가 표시될 수 있습니다.
error: Dict entry 0 has incompatible type "str": "int"; expected "Mapping[str, Any]": "int"
해결 방법은 MongoClient
객체 에 다음 유형 힌트를 추가하는 것입니다.
``client: MongoClient[Dict[str, Any]]``
목록을 insert_one()
메서드에 전달하면 유사한 오류가 표시될 수 있습니다.
error: Argument 1 to "insert_one" of "Collection" has incompatible type "List[Dict[<nothing>, <nothing>]]"; expected "Mapping[str, Any]"
이 오류는 insert_one()
메서드가 목록이 아닌 문서 허용하기 때문에 발생합니다. 이 오류는 문서 insert_one()
메서드에 전달하거나 대신 insert_many()
메서드를 호출하여 해결할 수 있습니다.
TypedDict _id 키 누락
_id
필드 지정하지 않으면 PyMongo 해당 필드를 문서 에 자동으로 삽입합니다. 런타임에 _id
필드 의 값을 조회 할 수 있지만, MyPy 또는 다른 도구를 사용하여 정적 유형 검사를 수행하는 경우 클래스에서 _id
필드 를 찾을 수 없으며 다음과 유사한 오류가 표시됩니다. 다음을 수행합니다.
TypedDict has no key "_id"
이는 다음과 유사한 코드로 인해 발생합니다.
from typing import TypedDict from pymongo import MongoClient from pymongo.collection import Collection class Movie(TypedDict): name: str year: int client: MongoClient = MongoClient() collection: Collection[Movie] = client.test.test inserted = collection.insert_one(Movie(name="Jurassic Park", year=1993)) result = collection.find_one({"name": "Jurassic Park"}) # _id is present but was added by PyMongo; this will raise a type-checking error assert result["_id"]
한 가지 해결책은 _id
필드 사용하는 줄 끝에 # type:ignore
주석을 추가하는 것입니다. 이 주석은 유형 검사 도구가 해당 행으로 인해 발생하는 모든 오류를 무시하도록 지시합니다. 다음 예시 이 솔루션을 구현 방법을 보여줍니다.
from typing import TypedDict from pymongo import MongoClient from pymongo.collection import Collection class Movie(TypedDict): name: str year: int collection: Collection[Movie] = client.test.test inserted = collection.insert_one( Movie(name="Jurassic Park", year=1993) ) result = collection.find_one({"name": "Jurassic Park"}) assert result is not None assert result["_id"] # type:ignore[typeddict-item]
유형 오류를 무시하는 대신 모델 클래스에 _id
필드 포함하고 클래스 인스턴스 를 만들 때 이 필드 의 값을 명시적으로 지정하여 오류를 방지할 수 있습니다. 다음 코드는 이 솔루션을 구현 방법을 보여줍니다.
from typing import TypedDict from pymongo import MongoClient from pymongo.collection import Collection from bson import ObjectId class Movie(TypedDict): _id: ObjectId name: str year: int collection: Collection[ExplicitMovie] = client.test.test inserted = collection.insert_one( ExplicitMovie(_id=ObjectId(), name="Jurassic Park", year=1993) ) result = collection.find_one({"name": "Jurassic Park"}) assert result is not None assert result["_id"]
사용자 지정 클래스에 _id
필드 추가할 때의 한 가지 단점은 생성하는 클래스의 모든 인스턴스 에 대해 필드 값을 포함해야 한다는 것입니다. 이를 방지하려면 NotRequired
유형 힌트가 포함된 typing.NotRequired
패키지 설치할 수 있습니다. 이 유형 힌트를 _id
필드 에 사용하면 컴파일 타임 유형 오류 없이 런타임에 _id
필드 값에 액세스 할 수 있습니다.
다음 코드 예시 이 솔루션을 구현 방법을 보여줍니다.
from typing import TypedDict, NotRequired from pymongo import MongoClient from pymongo.collection import Collection from bson import ObjectId class Movie(TypedDict): _id: NotRequired[ObjectId] name: str year: int client: MongoClient = MongoClient() collection: Collection[Movie] = client.test.test inserted = collection.insert_one(Movie(name="Jurassic Park", year=1993)) result = collection.find_one({"name": "Jurassic Park"}) assert result is not None assert result["_id"]
중요
NotRequired Python 3.11+ 필요
NotRequired 클래스는 Python 3.11 이상에서만 사용할 수 있습니다. 이전 버전의 Python 에서 을(를) 사용하려면 대신 NotRequired
타이핑_확장 패키지 설치하세요.
추가 정보
PyMongo 로 문서를 삽입하는 실행 가능한 코드 예제는 CRUD 작업을 참조하세요.
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.