AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

문서 삽입

이 가이드에서는 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에 대한 자세한 내용은 고유 인덱스에 대한 서버 매뉴얼 항목을 참조하세요.

단일 문서를 삽입하려면 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 연결 가이드를 참조하세요. 이 예시에서는 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기에 따라 MongoDB Atlas의 무료 클러스터에 있는 데이터베이스에 로드할 수 있습니다.

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

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>"; // Create a new client and connect to MongoDBconst client = new MongoClient(uri); async function run() { try { // Connect to the "sample_mflix" database and access its "movies" collection const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a document to insert const doc = { title: "Charade", genres: ["Comedy", "Romance", "Thriller"], year: 1963, cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], } // Insert the defined document into the "movies" collection const result = await movies.insertOne(doc); // Print the ID of the inserted document console.log(`A document was inserted with the _id: ${result.insertedId}`); } finally { // Close the MongoDB client connection await client.close(); }}// Run the function and handle any errorsrun().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" }

앞의 문서를 insertMany() 메서드에 전달하면 드라이버 첫 번째 문서와 두 번째 문서를 삽입하지만 ID 1 가 중복되기 때문에 세 번째 문서 에 대해서는 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 1Processed a document with id 2Processed a document with id 1Processed a document with id 3Number 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 60ca09f4a40cf1d1afcd93a2Inserted a document with id 60ca09f4a40cf1d1afcd93a3Inserted a document with id 60ca09f4a40cf1d1afcd93a4

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

참고

설정 예시

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

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

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create an array of documents to insert const moviesToInsert = [ { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, ]; // Prevent additional documents from being inserted if one fails const options = { ordered: true }; // Execute insert operation const result = await movies.insertMany(moviesToInsert, options); // Print result console.log(`${result.insertedCount} documents were inserted`); } finally { await client.close(); }}run().catch(console.dir);

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

3 documents were inserted

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