Docs Menu
Docs Home
/ / /
Node.js 드라이버
/

문서 삽입

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

MongoDB를 사용하여 MongoDB에 이미 저장된 정보를 조회, 업데이트 및 삭제할 수 있습니다. 정보를 저장하려면 삽입 작업을 사용합니다.

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

  • insertOne()

  • insertMany()

  • bulkWrite()

인터랙티브 랩

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

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

다음 섹션에서는 insertOne() 및 에 중점을 insertMany() 둡니다. 메서드 사용 방법에 대한 bulkWrite() 예시는 대량 작업 가이드bulkWrite() 예제: 전체 파일 섹션을 참조하세요.

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

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

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

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

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

참고

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

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

단일 문서를 삽입하려면 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

이 섹션에 언급된 클래스 및 메서드에 대한 자세한 내용은 다음 리소스를 참조하세요.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoDB 에 연결 가이드 참조하세요. 이 예시 movies sample_mflix Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 코드는 삽입 작업을 수행하는 완전한 독립형 파일 입니다.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6// Create a new client and connect to MongoDB
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 // Connect to the "sample_mflix" database and access its "movies" collection
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a document to insert
16 const doc = {
17 title: "Charade",
18 genres: ["Comedy", "Romance", "Thriller"],
19 year: 1963,
20 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"],
21 }
22 // Insert the defined document into the "movies" collection
23 const result = await movies.insertOne(doc);
24
25 // Print the ID of the inserted document
26 console.log(`A document was inserted with the _id: ${result.insertedId}`);
27 } finally {
28 // Close the MongoDB client connection
29 await client.close();
30 }
31}
32// Run the function and handle any errors
33run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10 content: string[];
11 year: number;
12 cast: string[];
13}
14
15async function run() {
16 try {
17 const database = client.db("sample_mflix");
18 // Specifying a Schema is optional, but it enables type hints on
19 // finds and inserts
20 const movies = database.collection<Movie>("movies");
21 const result = await movies.insertOne({
22 title: "Charade",
23 genres: ["Comedy", "Romance", "Thriller"],
24 year: 1963,
25 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"],
26 });
27 console.log(`A document was inserted with the _id: ${result.insertedId}`);
28 } finally {
29 await client.close();
30 }
31}
32run().catch(console.dir);

앞의 예시를 실행하면 다음과 같은 결과가 출력됩니다.

A document was inserted with the _id: ...

여러 문서를 삽입하려는 경우 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

이 섹션에 언급된 클래스 및 메서드에 대한 자세한 내용은 다음 리소스를 참조하세요.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoDB 에 연결 가이드 참조하세요. 이 예시 movies sample_mflix Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 코드는 다수 삽입 작업을 수행하는 완전한 독립형 파일 입니다.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create an array of documents to insert
16 const moviesToInsert = [
17 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
18 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
19 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
20 ];
21
22 // Prevent additional documents from being inserted if one fails
23 const options = { ordered: true };
24
25 // Execute insert operation
26 const result = await movies.insertMany(moviesToInsert, options);
27
28 // Print result
29 console.log(`${result.insertedCount} documents were inserted`);
30 } finally {
31 await client.close();
32 }
33}
34run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10 genres: string[];
11 year: number;
12 cast: string[];
13}
14
15async function run() {
16 try {
17 const database = client.db("sample_mflix");
18 // Specifying a schema is optional, but it enables type hints on
19 // finds and inserts
20 const movies = database.collection<Movie>("movies");
21
22 const result = await movies.insertMany(
23 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
24 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
25 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
26 { ordered: true }
27 );
28 console.log(`${result.insertedCount} documents were inserted`);
29 } finally {
30 await client.close();
31 }
32}
33run().catch(console.dir);

앞의 예시를 실행하면 다음과 같은 결과가 출력됩니다.

3 documents were inserted

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

CRUD 작업

이 페이지의 내용

  • 개요
  • 참고 사항 _id
  • 단일 문서 삽입
  • 예시
  • insertOne() 예제: 전체 파일
  • 여러 문서를 삽입합니다.
  • 예시
  • insertMany() 예제: 전체 파일
  • API 문서