문서 삽입
개요
이 가이드 에서는 삽입 작업 을 수행하여 MongoDB PHP 라이브러리를 사용하여 MongoDB 컬렉션 에 문서를 추가하는 방법을 학습 수 있습니다.
삽입 작업은 하나 이상의 문서를 MongoDB 컬렉션 에 삽입합니다. 다음 메서드를 사용하여 삽입 작업을 수행할 수 있습니다.
MongoDB\Collection::insertOne()
단일 문서 를 삽입하는 메서드MongoDB\Collection::insertMany()
하나 이상의 문서를 삽입하는 메서드
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트 의 sample_restaurants
데이터베이스 에 있는 restaurants
컬렉션 을 사용합니다. PHP 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 MongoDB\Client
를 인스턴스화하고 $collection
변수에 다음 값을 할당합니다.
$collection = $client->sample_restaurants->restaurants;
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
_id
필드
MongoDB 컬렉션에서 각 문서에는 고유한 필드 값이 있는 _id
필드가 포함되어야 합니다.
MongoDB를 사용하면 이 필드를 두 가지 방법으로 관리할 수 있습니다.
각 문서 의
_id
필드 를 직접 설정하여 각 값이 고유하도록 합니다.운전자 가 각 문서
_id
필드 에 대해 고유한ObjectId
값을 자동으로 생성하도록 합니다.
고유성을 보장할 수 없는 경우 드라이버가 _id
값을 자동으로 생성하도록 하는 것이 좋습니다.
참고
중복된 _id
값은 고유 인덱스 제약 조건을 위반하여 운전자 가 MongoDB\Driver\Exception\BulkWriteException
오류를 반환하도록 합니다.
_id
필드에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 고유 인덱스 가이드를 참조하세요.
문서 구조 및 규칙에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 가이드를 참조하세요.
문서 하나 삽입
MongoDB 컬렉션에 단일 문서를 추가하려면 MongoDB\Collection::insertOne()
메서드를 호출하고 추가하려는 문서를 전달합니다.
다음 예시에서는 restaurants
컬렉션에 문서를 삽입합니다.
$result = $collection->insertOne(['name' => 'Mongo\'s Burgers']);
여러 문서를 삽입합니다.
MongoDB 컬렉션 에 여러 문서를 추가하려면 MongoDB\Collection::insertMany()
메서드를 호출하고 추가하려는 문서 목록이 포함된 배열 을 전달합니다.
다음 예시 에서는 restaurants
컬렉션 에 두 개의 문서를 삽입합니다.
$restaurants = [ ['name' => 'Mongo\'s Burgers'], ['name' => 'Mongo\'s Pizza'] ]; $result = $collection->insertMany($restaurants);
삽입 동작 수정
옵션 값을 매개 변수로 지정하는 배열 을 전달하여 MongoDB\Collection::insertOne()
및 MongoDB\Collection::insertMany()
메서드의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 몇 가지 옵션을 설명합니다.
필드 | 설명 |
---|---|
| If set to true , allows the write operation to opt out of
document-level validation.Defaults to false .Type: bool |
| Sets the write concern for the operation. Defaults to the write concern of the namespace. Type: MongoDB\Driver\WriteConcern |
| If set to true , the operation stops inserting documents when one insert
fails. If false , the operation continues to insert the remaining documents
when one insert fails. You cannot pass this option to the insertOne() method.Defaults to true .Type: bool |
| A comment to attach to the operation. For more information, see the insert command
fields guide in the
MongoDB Server manual. Type: any valid BSON type |
예시
다음 코드에서는 insertMany()
메서드를 사용하여 컬렉션 에 세 개의 새 문서를 삽입합니다. 옵션 배열 에서 bypassDocumentValidation
필드 가 true
로 설정하다 되어 있으므로 이 삽입 작업은 문서 수준 유효성 검사 를 우회합니다.
$docs = [ ['name' => 'Mongo\'s Burgers'], ['name' => 'Mongo\'s Pizza'], ['name' => 'Mongo\'s Tacos'] ]; $result = $collection->insertMany($docs, ['bypassDocumentValidation' => true]);
추가 정보
MongoDB PHP 라이브러리를 사용하여 문서를 삽입하는 실행 가능한 코드 예제를 보려면 MongoDB 에 데이터 쓰기를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.