MongoDB Atlas 통합

MongoDB Atlas 통합

LangChain JavaScript로 MongoDB Atlas 벡터 스토어와 통합해요.

**호환성**: Node.js에서만 사용할 수 있어요.

Next.js에서도 runtime 변수를 nodejs로 설정해 MongoDB를 사용하는 API 라우트를 만들 수 있어요:

export const runtime = "nodejs";

자세한 내용은 Next.js 문서의 Edge runtimes를 참고하세요.

이 가이드는 MongoDB Atlas 벡터 스토어 시작을 위한 빠른 개요를 제공해요. 모든 MongoDBAtlasVectorSearch 기능과 구성에 대한 자세한 문서는 API reference를 참고하세요.

개요 (Overview)

통합 세부 정보 (Integration details)

클래스 패키지 PY 지원 Version
MongoDBAtlasVectorSearch @langchain/mongodb NPM - Version

설정 (Setup)

MongoDB Atlas 벡터 스토어를 사용하려면 MongoDB Atlas 클러스터를 구성하고 @langchain/mongodb 통합 패키지를 설치해야 해요.

초기 클러스터 구성 (Initial Cluster Configuration)

MongoDB Atlas 클러스터를 만들려면 MongoDB Atlas 웹사이트로 이동하고 계정이 없다면 만드세요.

프롬프트가 나오면 클러스터를 만들고 이름을 지정한 뒤 Database에서 찾으세요. Browse Collections를 선택하고 빈 컬렉션 또는 제공된 샘플 데이터 중 하나를 만드세요.

Note: 수동 임베딩 모드에는 클러스터가 MongoDB 7.0 이상이어야 해요. 자동 임베딩 모드에는 MongoDB 8.2 이상이 필요해요.

벡터 검색 인덱스 생성 (Creating a Vector Search Index)

클러스터를 구성한 뒤 컬렉션에 벡터 검색 인덱스를 만드세요. Atlas, Compass, MongoDB Shell에서 할 수 있어요. 인덱스 정의는 사용하는 임베딩 모드에 따라 달라져요.

수동 임베딩 (MongoDB 7.0+): 문서를 클라이언트에서 임베딩하고 벡터를 필드에 저장해요. 다음 정의를 사용하되 numDimensions를 임베딩 모델에 맞게 조정하세요.

{
  "name": "index_name",
  "type": "vectorSearch",
  "definition": {
    "fields": [
      {
        "numDimensions": 1536,
        "path": "embedding",
        "similarity": "euclidean",
        "type": "vector"
      }
    ]
  }
}

자동 임베딩 (MongoDB 8.2+): MongoDB가 Voyage AI 모델로 서버 측에서 임베딩을 생성해요. autoEmbed 필드 타입을 사용하고 모델을 지정하세요:

{
  "name": "index_name",
  "type": "vectorSearch",
  "definition": {
    "fields": [
      {
        "type": "autoEmbed",
        "modality": "text",
        "path": "textContent",
        "model": "voyage-4"
      }
    ]
  }
}

기본적으로 벡터 스토어는 text라는 텍스트 필드에서 읽고 (수동 모드에서) embedding이라는 필드에 벡터를 써요. textKeyembeddingKey를 인덱스에 맞게 설정하세요.

const vectorStore = new MongoDBAtlasVectorSearch(
  embeddings,                  // omit in auto embedding mode
  {
    collection,
    indexName: "index_name",
    textKey: "textContent",    // document field where raw text is stored
    embeddingKey: "embedding", // matches "path" (omit in auto embedding mode)
  }
);

인덱스 생성을 진행하세요.

임베딩 (Embeddings)

수동 임베딩 모드에서는 임베딩 모델을 제공하고 문서를 클라이언트에서 임베딩해요. 이 가이드는 OpenAI 임베딩을 예시로 사용해요. 다른 지원 임베딩 모델도 사용할 수 있어요.

자동 임베딩 모드에서는 MongoDB Atlas가 서버 측에서 임베딩 생성을 처리해요. 클라이언트 측 임베딩 패키지가 필요하지 않아요.

설치 (Installation)

수동 임베딩: 핵심 패키지와 임베딩 제공자를 설치하세요.

```bash npm npm install @langchain/mongodb mongodb @langchain/core @langchain/openai ```
yarn add @langchain/mongodb mongodb @langchain/core @langchain/openai
pnpm add @langchain/mongodb mongodb @langchain/core @langchain/openai

자동 임베딩: 핵심 패키지와 MongoDB 드라이버만 필요해요.

```bash npm npm install @langchain/mongodb mongodb @langchain/core ```
yarn add @langchain/mongodb mongodb @langchain/core
pnpm add @langchain/mongodb mongodb @langchain/core

자격 증명 (Credentials)

위 단계를 완료한 뒤 Mongo 대시보드의 Connect 버튼에서 MONGODB_ATLAS_URI 환경 변수를 설정하세요. DB 이름과 컬렉션 이름도 필요해요:

process.env.MONGODB_ATLAS_URI = "your-atlas-URL";
process.env.MONGODB_ATLAS_COLLECTION_NAME = "your-atlas-collection-name";
process.env.MONGODB_ATLAS_DB_NAME = "your-atlas-db-name";

OpenAI로 수동 임베딩 모드를 사용한다면 OpenAI 키도 설정하세요:

process.env.OPENAI_API_KEY = "YOUR_API_KEY";

자동 임베딩 모드에서는 추가 API 키가 필요하지 않아요 — MongoDB Atlas가 인덱스에 구성된 모델로 임베딩 생성을 처리해요.

모델 호출의 자동 추적을 받으려면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:

// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"

인스턴스화 (Instantiation)

클러스터와 인덱스를 설정한 뒤 벡터 스토어를 초기화하세요. 생성자는 수동 임베딩을 사용하는지 자동 임베딩을 사용하는지에 따라 두 가지 형태를 받아요.

수동 임베딩: 첫 번째 인자로 임베딩 인스턴스를 전달하세요.

import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
import { OpenAIEmbeddings } from "@langchain/openai";
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_ATLAS_URI!);
const collection = client
  .db(process.env.MONGODB_ATLAS_DB_NAME)
  .collection(process.env.MONGODB_ATLAS_COLLECTION_NAME);

const embeddings = new OpenAIEmbeddings({
  model: "text-embedding-3-small",
});

const vectorStore = new MongoDBAtlasVectorSearch(embeddings, {
  collection,
  indexName: "vector_index", // Defaults to "default"
  textKey: "text",           // Defaults to "text"
  embeddingKey: "embedding", // Defaults to "embedding"
});

자동 임베딩: 구성 객체만 전달하세요 (임베딩 인자 불필요).

import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_ATLAS_URI!);
const collection = client
  .db(process.env.MONGODB_ATLAS_DB_NAME)
  .collection(process.env.MONGODB_ATLAS_COLLECTION_NAME);

const vectorStore = new MongoDBAtlasVectorSearch({
  collection,
  indexName: "default", // Must match the index name in your Atlas cluster
});

벡터 스토어 관리 (Manage vector store)

벡터 스토어에 항목 추가 (Add items to vector store)

이제 벡터 스토어에 문서를 추가할 수 있어요:

import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "The powerhouse of the cell is the mitochondria",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "Buildings are made out of brick",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "Mitochondria are made out of lipids",
  metadata: { source: "https://example.com" }
};

const document4: Document = {
  pageContent: "The 2024 Olympics are in Paris",
  metadata: { source: "https://example.com" }
}

const documents = [document1, document2, document3, document4];

await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });
문서를 추가한 후 쿼리 가능해지기까지 지연이 있어요. 자동 임베딩 모드에서는 삽입 후 MongoDB가 서버 측에서 임베딩을 생성해야 하므로 지연이 더 길어요. Atlas 검색 인덱스가 문서가 인덱싱됐다고 보고할 때까지 기다렸다가 쿼리하세요.

기존 문서와 같은 id로 문서를 추가하면 기존 문서를 업데이트해요.

벡터 스토어에서 항목 삭제 (Delete items from vector store)

await vectorStore.delete({ ids: ["4"] });

벡터 스토어 쿼리 (Query vector store)

직접 쿼리 (Query directly)

간단한 유사도 검색은 다음과 같이 수행할 수 있어요:

const similaritySearchResults = await vectorStore.similaritySearch("biology", 2);

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]

필터링 (Filtering)

MongoDB Atlas는 다른 필드에 대한 결과 사전 필터링을 지원해요. 이를 위해 처음 만든 인덱스를 업데이트해 필터링할 메타데이터 필드를 정의해야 해요. 예시:

{
  "fields": [
    {
      "numDimensions": 1024,
      "path": "embedding",
      "similarity": "euclidean",
      "type": "vector"
    },
    {
      "path": "source",
      "type": "filter"
    }
  ]
}

위에서 fields의 첫 번째 항목은 벡터 인덱스이고, 두 번째 항목은 필터링할 메타데이터 속성이에요. 속성 이름은 path 키의 값이에요. 따라서 위 인덱스는 source라는 메타데이터 필드로 검색할 수 있게 해줘요.

그런 다음 코드에서 MQL Query Operators를 사용해 필터링할 수 있어요.

아래 예제가 이를 보여줘요:

const filter = {
  preFilter: {
    source: {
      $eq: "https://example.com",
    },
  },
}

const filteredResults = await vectorStore.similaritySearch("biology", 2, filter);

for (const doc of filteredResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}

점수 반환 (Returning scores)

유사도 검색을 실행하고 대응하는 점수를 받으려면 다음을 실행할 수 있어요:

const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2, filter)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
* [SIM=0.374] The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* [SIM=0.370] Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]

리트리버로 변환해 쿼리 (Query by turning into retriever)

벡터 스토어를 리트리버로 변환해 체인에서 더 쉽게 사용할 수도 있어요.

const retriever = vectorStore.asRetriever({
  // Optional filter
  filter: filter,
  k: 2,
});
await retriever.invoke("biology");

검색 증강 생성(RAG) 사용법 (Usage for retrieval-augmented generation)

이 벡터 스토어를 검색 증강 생성(RAG)에 사용하는 방법에 대한 가이드는 다음 섹션을 참고하세요:

연결 닫기 (Closing connections)

과도한 리소스 소비를 피하기 위해 작업이 끝나면 클라이언트 인스턴스를 닫으세요:

await client.close();

API reference

모든 MongoDBAtlasVectorSearch 기능과 구성에 대한 자세한 문서는 API reference를 참고하세요.

출처: 문서

본문

MongoDBAtlasVectorSearch는 MongoDB Atlas 벡터 검색용 통합이에요. @langchain/mongodb 패키지에서 가져와 수동 임베딩(임베딩 인스턴스 + textKey·embeddingKey) 또는 자동 임베딩(MongoDB 8.2+, autoEmbed 인덱스)으로 구성해요. 문서 추가(UUID id, 동일 id 업데이트)·삭제, similaritySearch(MQL preFilter 포함)·similaritySearchWithScore·asRetriever()를 지원하며, 작업 후 client.close()로 연결을 닫아요.

더 알아보기 (Learn more)