Docs Menu
Docs Home
/ / /
Node.js
/ / /

문서 삽입

이 페이지의 내용

  • 개요
  • 참고 사항 _id
  • 단일 문서 삽입
  • 여러 문서를 삽입합니다.

이 가이드에서는 MongoDB에 문서를 삽입하는 방법을 배울 수 있습니다.

MongoDB를 사용하여 정보를 검색, 업데이트 및 삭제할 수 있습니다. 이러한 작업을 수행하려면 사용자 프로필 및 주문 등 필요한 정보가 MongoDB에 있어야 합니다. 해당 정보가 존재하려면 먼저 삽입 작업을 수행해야 합니다.

삽입 작업은 하나 이상의 문서를 MongoDB 컬렉션에 삽입하는 작업입니다. Node.js 드라이버는 삽입 작업을 수행하기 위해 다음과 같은 메서드를 제공합니다:

  • insertOne()

  • insertMany()

  • bulkWrite()

인터랙티브 랩

이 페이지에는 insertOne() 메서드를 사용하여 데이터를 삽입하는 방법을 보여주는 짧은 대화형 실습이 포함되어 있습니다. MongoDB 또는 코드 편집기를 설치하지 않고도 브라우저 창에서 직접 이 실습을 완료할 수 있습니다.

실습을 시작하려면 페이지 상단의 Open Interactive Tutorial 버튼을 클릭하세요. 실습을 전체 화면 형식으로 확장하려면 실습 창의 오른쪽 상단 모서리에 있는 전체 화면 버튼()을 클릭합니다.

다음 섹션에서는 insertOne()insertMany() 에 중점을 둡니다. bulkWrite() 메서드 사용 방법에 대한 예시 는 실행 가능한 대량 작업 예시를 참조하세요.

문서를 삽입할 때 MongoDB는 기본적으로 문서에 하나의 제약 조건을 적용합니다. 각 문서에는 고유한 _id 필드가 반드시 포함되어야 합니다.

이 필드를 관리하는 방법에는 두 가지가 있습니다:

  • 각 값이 고유하게 유지되도록 해당 필드를 직접 관리할 수 있습니다.

  • 드라이버는 기본 키 팩토리를 사용해 고유한 ObjectId 값을 자동으로 생성할 수 있습니다.

고유성에 대한 강력한 보장을 제공하지 않는 한, 드라이버가 자동으로 _id 값을 생성하도록 하는 것이 좋습니다.

참고

중복된 _id 값은 고유 인덱스 제약 조건을 위반하여 WriteError가 발생합니다.

_id 에 대한 자세한 내용은 고유 인덱스에 대한 서버 수동 항목을 참조하세요.

단일 문서를 삽입하려면 insertOne() 메서드를 사용합니다.

삽입이 성공하면 메서드는 새 문서의 _id를 나타내는 InsertOneResult 인스턴스를 반환합니다.

다음 예에서는 insertOne() 메서드를 사용하여 새 문서를 myDB.pizzaMenu collection에 삽입합니다.

const myDB = client.db("myDB");
const myColl = myDB.collection("pizzaMenu");
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await myColl.insertOne(doc);
console.log(
`A document was inserted with the _id: ${result.insertedId}`,
);

결과물은 다음과 같이 표시되어야 합니다:

A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836

이 섹션에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 리소스를 참조하세요.

여러 문서를 삽입하려는 경우 insertMany() 메서드를 사용합니다. 이 메소드는 예외가 발생할 때까지 지정된 순서대로 문서를 삽입합니다.

예를 들어, 다음 문서를 삽입한다고 가정합니다.

{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }
{ "_id": 1, "color": "yellow" }
{ "_id": 3, "color": "blue" }

해당 문서를 삽입하려고 하던 중 세 번째 문서에 WriteError 오류가 발생할 경우, 오류가 발생하기 전의 문서는 이미 컬렉션에 삽입된 상태가 됩니다.

참고

try-catch 차단을 사용하면 오류가 발생하기 전에 성공적으로 처리된 문서에 대한 승인을 받을 수 있습니다.

const myDB = client.db("myDB");
const myColl = myDB.collection("colors");
try {
const docs = [
{ "_id": 1, "color": "red"},
{ "_id": 2, "color": "purple"},
{ "_id": 1, "color": "yellow"},
{ "_id": 3, "color": "blue"}
];
const insertManyresult = await myColl.insertMany(docs);
let ids = insertManyresult.insertedIds;
console.log(`${insertManyresult.insertedCount} documents were inserted.`);
for (let id of Object.values(ids)) {
console.log(`Inserted a document with id ${id}`);
}
} catch(e) {
console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`);
let ids = e.result.result.insertedIds;
for (let id of Object.values(ids)) {
console.log(`Processed a document with id ${id._id}`);
}
console.log(`Number of documents inserted: ${e.result.result.nInserted}`);
}

출력은 MongoDB가 처리할 수 있는 문서로 구성되며 다음과 같이 표시됩니다.

A MongoBulkWriteException occurred, but there are successfully processed documents.
Processed a document with id 1
Processed a document with id 2
Processed a document with id 1
Processed a document with id 3
Number of documents inserted: 2

Collection 내부를 살펴보면 다음과 같은 문서가 표시됩니다.

{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }

삽입에 성공하면 메서드는 삽입된 문서 수를 나타내는 InsertManyResult 인스턴스와 새 문서의 _id를 반환합니다.

다음 예에서는 insertMany() 메서드를 사용하여 세 개의 새 문서를 myDB.pizzaMenu collection에 삽입합니다.

const myDB = client.db("myDB");
const myColl = myDB.collection("pizzaMenu");
const docs = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" }
];
const insertManyresult = await myColl.insertMany(docs);
let ids = insertManyresult.insertedIds;
console.log(`${insertManyresult.insertedCount} documents were inserted.`);
for (let id of Object.values(ids)) {
console.log(`Inserted a document with id ${id}`);
}

결과물은 다음과 같이 표시되어야 합니다:

3 documents were inserted.
Inserted a document with id 60ca09f4a40cf1d1afcd93a2
Inserted a document with id 60ca09f4a40cf1d1afcd93a3
Inserted a document with id 60ca09f4a40cf1d1afcd93a4

이 섹션에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 리소스를 참조하세요.

돌아가기

쓰기 작업