문서 메뉴
문서 홈
/ / /
Node.js
/ /

여러 문서를 삽입합니다.

collection.insertMany() 메서드를 사용하여 여러 문서를 삽입할 수 있습니다. insertMany()는 지정된 컬렉션에 삽입할 문서 배열을 사용합니다.

insertMany()메서드의 두 번째 매개변수로 전달된 options 객체에 추가 옵션을 지정할 수 있습니다. 배열의 이전 문서에 대한 삽입이 실패한 경우 나머지 문서를 삽입하지 않으려면 ordered:true 지정하세요.

insertMany() 작업에 잘못된 매개변수를 지정하면 문제가 발생할 수 있습니다. 고유 인덱스 규칙을 위반하는 값에 필드를 삽입하려고 하면 duplicate key error가 발생합니다.

참고

이 예제를 사용하여 MongoDB 인스턴스에 연결하고 샘플 데이터가 포함된 데이터베이스와 상호 작용할 수 있습니다. MongoDB 인스턴스에 연결하고 샘플 데이터 세트를 로드하는 방법에 대해 자세히 알아보려면 사용 예제 가이드를 참조하세요.

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("insertDB");
13 const foods = database.collection("foods");
14
15 // Create an array of documents to insert
16 const docs = [
17 { name: "cake", healthy: false },
18 { name: "lettuce", healthy: true },
19 { name: "donut", healthy: false }
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 foods.insertMany(docs, 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 Food {
9 name: string;
10 healthy: boolean;
11}
12
13async function run() {
14 try {
15 const database = client.db("insertDB");
16 // Specifying a schema is optional, but it enables type hints on
17 // finds and inserts
18 const foods = database.collection<Food>("foods");
19
20 const result = await foods.insertMany(
21 [
22 { name: "cake", healthy: false },
23 { name: "lettuce", healthy: true },
24 { name: "donut", healthy: false },
25 ],
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

돌아가기

문서 삽입