참고
이 튜토리얼에서는 LangChain의 JavaScript 라이브러리를 사용합니다. Python 라이브러리를 사용하는 튜토리얼은 LangChain Python참조하세요.
MongoDB Vector Search를 LangChain 과 통합하여 LLM 애플리케이션을 빌드 하고 RAG(검색 강화 생성)를 구현 수 있습니다. 이 튜토리얼에서는 MongoDB Vector Search를 LangChain과 함께 사용하여 데이터에 시맨틱 검색 수행하고 RAG 구현 빌드 방법을 보여 줍니다. 구체적으로 다음 조치를 수행합니다.
환경을 설정합니다.
사용자 지정 데이터를 MongoDB 에 저장합니다.
데이터에 MongoDB Vector Search 인덱스 생성합니다.
다음 벡터 검색 쿼리를 실행합니다.
시맨틱 검색.
메타데이터 사전 필터링을 통한 시맨틱 검색.
최대 한계 관련성(MMR) Atlas Search.
MongoDB Vector Search를 사용하여 데이터에 대한 질문에 답변 RAG 를 구현합니다.
배경
LangChain은 '체인'을 사용하여 LLM 애플리케이션 생성을 간소화하는 오픈 소스 프레임워크 입니다. 체인은 RAG를 포함한 다양한 AI 사용 사례에 결합할 수 있는 LangChain 전용 구성 요소입니다.
MongoDB Vector Search를 LangChain과 통합하면 MongoDB 벡터 데이터베이스로 사용하고 MongoDB Vector Search를 사용하여 데이터에서 의미적으로 유사한 문서를 검색하여 RAG 를 구현. RAG에 대해 자세히 학습 MongoDB 사용한 검색-증강 생성(RAG)을 참조하세요.
전제 조건
이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 버전 6.0.11을 실행하는 Atlas 클러스터 7.0.2 또는 그 이상. IP 주소가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Atlas CLI 사용하여 생성된 로컬 Atlas 배포서버 입니다. 자세히 학습 로컬 Atlas 배포 만들기를 참조하세요.
검색 및 벡터 검색이 설치된 MongoDB Community 또는 Enterprise 클러스터.
Voyage AI API 키입니다. 계정과 API 키를 만들려면 Voyage AI 웹사이트참조하세요.
OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대해 자세히 학습하려면 OpenAI API 웹사이트를 참조하세요.
Node.js 프로젝트를 실행하기 위한 터미널 및 코드 편집기입니다.
npm 및 Node.js 가 설치되어 있어야 합니다.
환경 설정
이 튜토리얼의 환경을 설정합니다. 환경을 설정하다 하려면 다음 단계를 완료하세요.
package.json 파일을 업데이트합니다.
package.json 파일에 "type": "module" 를 추가한 다음 저장하여 ES 모듈 을 사용하도록 프로젝트 구성합니다.
{ "type": "module", // other fields... }
get-started.js라는 이름의 파일을 생성하고 다음 코드를 붙여넣습니다.
프로젝트에서 get-started.js 파일을 만든 다음, 다음 코드를 복사하여 파일에 붙여넣습니다. 튜토리얼 전체에서 이 파일에 코드를 추가합니다.
이 초기 코드 스니펫은 이 튜토리얼에 필요한 패키지를 가져오고, 환경 변수를 정의하고, MongoDB cluster 에 대한 연결을 설정합니다.
import { formatDocumentsAsString } from "langchain/util/document"; import { MongoClient } from "mongodb"; import { MongoDBAtlasVectorSearch } from "@langchain/mongodb"; import { ChatOpenAI } from "@langchain/openai"; import { VoyageEmbeddings } from "@langchain/community/embeddings/voyage"; import { PDFLoader } from "@langchain/community/document_loaders/fs/pdf"; import { PromptTemplate } from "@langchain/core/prompts"; import { RecursiveCharacterTextSplitter } from "langchain/text_splitter"; import { RunnableSequence, RunnablePassthrough } from "@langchain/core/runnables"; import { StringOutputParser } from "@langchain/core/output_parsers"; import * as fs from 'fs'; process.env.VOYAGEAI_API_KEY = "<api-key>" process.env.OPENAI_API_KEY = "<api-key>"; process.env.MONGODB_URI = "<connection-string>"; const client = new MongoClient(process.env.MONGODB_URI);
자리 표시자 값을 바꿉니다.
환경 설정을 완료하려면 get-started.js 의 <api-key> 및 <connection-string> 자리 표시자 값을 각각 MongoDB cluster 의 Voyage AI API 키, OpenAI API 키 및 SRV 연결 문자열 로 바꿉니다. 연결 문자열 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
MongoDB 벡터 저장소로 사용
이 섹션에서는 사용자 지정 데이터를 MongoDB 에 로드하는 비동기 함수를 정의하고 MongoDB cluster 벡터 저장 라고도 하는 벡터 데이터베이스 로 인스턴스화합니다. get-started.js 파일 에 다음 코드를 추가합니다.
참고
이 튜토리얼에서는 공개적으로 액세스할 수 있는 MongoDB Atlas 모범 사례 라는 제목의 PDF 문서를 벡터 저장의 데이터 소스로 사용합니다. 이 문서 MongoDB 배포 관리를 위한 다양한 권장 사항과 핵심 개념에 대해 설명합니다.
이 코드는 다음 작업을 수행합니다.
다음 매개변수를 지정하여 MongoDB 컬렉션 구성합니다.
langchain_db.test문서를 저장 MongoDB 컬렉션 으로 지정합니다.vector_index를 벡터 저장소를 쿼리하는 데 사용할 인덱스로 사용합니다.text를 원시 텍스트 콘텐츠가 포함된 필드의 이름으로 지정합니다.embedding를 벡터 임베딩이 포함된 필드의 이름으로 지정합니다.
다음을 수행하여 사용자 지정 데이터를 준비합니다.
지정된 URL에서 원본 데이터를 검색하여 PDF로 저장합니다.
텍스트 분할기 를 사용하여 데이터를 작은 문서로 분할 .
각 문서의 문자 수와 두 개의 연속 문서 간에 겹치는 문자 수를 결정하는 청크 매개변수를 지정합니다.
MongoDBAtlasVectorSearch.fromDocuments메서드를 호출하여 샘플 문서에서 벡터 저장소를 만듭니다. 이 메서드는 다음 매개변수를 지정합니다.벡터 데이터베이스에 저장할 샘플 문서입니다.
텍스트를
embedding필드 의 벡터 임베딩으로 변환하는 데 사용되는 모델인Voyage AI의 임베딩 모델입니다.MongoDB cluster 구성.
async function run() { try { // Configure your MongoDB collection const database = client.db("langchain_db"); const collection = database.collection("test"); const dbConfig = { collection: collection, indexName: "vector_index", // The name of the MongoDB Search index to use. textKey: "text", // Field name for the raw text content. Defaults to "text". embeddingKey: "embedding", // Field name for the vector embeddings. Defaults to "embedding". }; // Ensure that the collection is empty const count = await collection.countDocuments(); if (count > 0) { await collection.deleteMany({}); } // Save online PDF as a file const rawData = await fetch("https://webassets.mongodb.com/MongoDB_Best_Practices_Guide.pdf"); const pdfBuffer = await rawData.arrayBuffer(); const pdfData = Buffer.from(pdfBuffer); fs.writeFileSync("atlas_best_practices.pdf", pdfData); // Load and split the sample data const loader = new PDFLoader(`atlas_best_practices.pdf`); const data = await loader.load(); const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 200, chunkOverlap: 20, }); const docs = await textSplitter.splitDocuments(data); // Instantiate MongoDB as a vector store const embeddingModel = new VoyageEmbeddings({ model: "voyage-3-large" }); const vectorStore = await MongoDBAtlasVectorSearch.fromDocuments(docs, embeddingModel, dbConfig); } finally { // Ensure that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
파일 저장한 후 다음 명령을 실행 데이터를 MongoDB 에 로드합니다.
node get-started.js
팁
get-started.js를 실행 후 Atlas 사용하는 경우 Atlas UI의 langchain_db.test 네임스페이스 로 이동하여 벡터 임베딩을 확인할 수 있습니다.
MongoDB Vector Search 인덱스 만들기
벡터 저장 에서 벡터 검색 쿼리를 활성화 하려면 langchain_db.test 컬렉션 에 MongoDB Vector Search 인덱스 만듭니다.
get-started.js 파일에 정의한 비동기 함수에 다음 코드를 추가합니다. 이 코드는 다음 필드를 인덱싱하는 vectorSearch 유형의 인덱스를 생성합니다.
embedding필드를 벡터 유형으로 지정합니다.embedding필드 에는 Voyage AI의voyage-3-large임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는1024벡터 차원을 지정하고cosine를 사용하여 유사성을 측정합니다.loc.pageNumber필드를 PDF의 페이지 번호를 기준으로 데이터를 사전 필터링하는 필터 유형으로 지정합니다.
또한 이 코드는 await 함수를 사용하여 검색 인덱스가 사용 전에 데이터와 동기화되었는지 확인합니다.
1 // Ensure index does not already exist, then create your MongoDB Vector Search index 2 const indexes = await collection.listSearchIndexes("vector_index").toArray(); 3 if(indexes.length === 0){ 4 5 // Define your MongoDB Vector Search Index 6 const index = { 7 name: "vector_index", 8 type: "vectorSearch", 9 definition: { 10 "fields": [ 11 { 12 "type": "vector", 13 "numDimensions": 1024, 14 "path": "embedding", 15 "similarity": "cosine" 16 }, 17 { 18 "type": "filter", 19 "path": "loc.pageNumber" 20 } 21 ] 22 } 23 } 24 25 // Run the helper method 26 const result = await collection.createSearchIndex(index); 27 console.log(result); 28 29 // Wait for index to build and become queryable 30 console.log("Waiting for initial sync..."); 31 await new Promise(resolve => setTimeout(() => { 32 resolve(); 33 }, 10000)); 34 }
파일 저장한 후 다음 명령을 실행 MongoDB Vector Search 인덱스 생성합니다.
node get-started.js
Vector Search 쿼리 실행
이 섹션에서는 벡터화된 데이터에 대해 실행할 수 있는 다양한 쿼리를 설명합니다. 이제 인덱스를 만들었으므로 비동기 함수에 다음 코드를 추가하여 데이터에 대해 벡터 Atlas Search 쿼리를 실행합니다.
참고
데이터를 쿼리할 때 부정확한 결과가 발생하는 경우 인덱스 동기화에 예상보다 시간이 오래 걸릴 수 있습니다. setTimeout 함수의 숫자를 늘려 초기 동기화에 더 많은 시간을 허용합니다.
비동기 함수에 다음 코드를 추가하고 파일을 저장합니다.
다음 코드는 similaritySearch 메서드를 사용하여 string MongoDB Atlas security에 대한 기본 시맨틱 검색을 수행합니다. 이 코드는 pageContent 및 pageNumber 필드만 포함하여 관련성에 따라 순위가 매겨진 문서 목록을 반환합니다.
// Basic semantic search const basicOutput = await vectorStore.similaritySearch("MongoDB Atlas security"); const basicResults = basicOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Semantic Search Results:") console.log(basicResults)
다음 명령을 실행하여 쿼리를 실행합니다.
node get-started.js
Semantic Search Results: [ { pageContent: 'Atlas free tier, or download MongoDB for local \n' + 'development.\n' + 'Review the MongoDB manuals and tutorials in our \n' + 'documentation. \n' + 'More Resources\n' + 'For more on getting started in MongoDB:', pageNumber: 30 }, { pageContent: 'read isolation. \n' + 'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' + 'tools like Atlas Charts can be configured to read from analytics nodes only.', pageNumber: 21 }, { pageContent: '• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\n' + 'Global Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or', pageNumber: 27 }, { pageContent: 'are updated, associated indexes must be maintained, incurring additional CPU and disk I/O overhead. \n' + 'If you\'re running fully managed databases on MongoDB Atlas, the built-in Performance Advisor', pageNumber: 20 } ]
인덱스된 필드를 컬렉션의 다른 값과 비교하는 MQL 일치 표현식을 사용하여 데이터를 사전 필터링할 수 있습니다. 필터링하려는 모든 메타데이터 필드를 filter 유형으로 인덱싱해야 합니다. 자세한 내용은 벡터 검색을 위해 필드를 인덱싱하는 방법을 참조하세요.
참고
이 튜토리얼 의 인덱스를 생성 할 때 loc.pageNumber 필드를 필터로 지정했습니다.
비동기 함수에 다음 코드를 추가하고 파일을 저장합니다.
다음 코드에서는 similaritySearch 메서드를 사용하여 문자열 MongoDB Atlas security에 대한 시맨틱 검색을 수행합니다. 다음 매개변수를 지정합니다.
3으로 반환할 문서 수$eq연산자를 사용하여 17 페이지에 나타나는 문서만 일치시키는loc.pageNumber필드에 대한 사전 필터입니다.
pageContent 및 pageNumber 필드만 사용하여 관련성에 따라 순위가 매겨진 문서 목록을 반환합니다.
// Semantic search with metadata filter const filteredOutput = await vectorStore.similaritySearch("MongoDB Atlas Search", 3, { preFilter: { "loc.pageNumber": {"$eq": 22 }, } }); const filteredResults = filteredOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Semantic Search with Filtering Results:") console.log(filteredResults)
다음 명령을 실행하여 쿼리를 실행합니다.
node get-started.js
Semantic Search with Filtering Results: [ { pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and', pageNumber: 22 }, { pageContent: 'Figure 9: Atlas Search queries are expressed through the MongoDB Query API and backed by the leading search engine library, \n' + 'Apache Lucene.', pageNumber: 22 }, { pageContent: 'consider using Atlas Search. The service is built on fully managed Apache Lucene but exposed to users \n' + 'through the MongoDB Aggregation Framework.', pageNumber: 22 } ]
다양성에 최적화된 의미적 관련성의 척도인 최대 한계 관련성(MMR)을 기반으로 시맨틱 검색을 수행할 수도 있습니다.
비동기 함수에 다음 코드를 추가하고 파일을 저장합니다.
다음 코드는 maxMarginalRelevanceSearch 메서드를 사용하여 문자열 MongoDB Atlas security를 검색합니다. 또한 다음 선택적 매개변수를 정의하는 객체를 지정합니다.
k반환되는 문서 수를3개로 제한합니다.fetchKMMR 알고리즘에 문서를 전달하기 전에10개 문서만 가져옵니다.
pageContent 및 pageNumber 필드만 사용하여 관련성에 따라 순위가 매겨진 문서 목록을 반환합니다.
// Max Marginal Relevance search const mmrOutput = await vectorStore.maxMarginalRelevanceSearch("MongoDB Atlas security", { k: 3, fetchK: 10, }); const mmrResults = mmrOutput.map((results => ({ pageContent: results.pageContent, pageNumber: results.metadata.loc.pageNumber, }))) console.log("Max Marginal Relevance Search Results:") console.log(mmrResults)
다음 명령을 실행하여 쿼리를 실행합니다.
node get-started.js
Max Marginal Relevance Search Results: [ { pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and', pageNumber: 22 }, { pageContent: '• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\n' + 'Global Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or', pageNumber: 27 }, { pageContent: 'read isolation. \n' + 'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' + 'tools like Atlas Charts can be configured to read from analytics nodes only.', pageNumber: 21 } ]
데이터에 대한 질문에 답변
이 섹션에서는 MongoDB Vector Search와 LangChain을 사용하여 두 가지 RAG를 구현하는 방법을 설명합니다. 이제 MongoDB Vector Search를 사용하여 의미적으로 유사한 문서를 조회 했으므로, 다음 코드 예제를 사용하여 LLM이 MongoDB Vector Search에서 반환된 문서에 대한 질문에 답변 하도록 프롬프트를 표시합니다.
비동기 함수에 다음 코드를 추가하고 파일을 저장합니다.
이 코드는 다음을 수행합니다.
LLM이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시하는 LangChain 프롬프트 템플릿 을 정의합니다. LangChain은 이러한 문서를
{context}입력 변수에 전달하고 쿼리{question}변수에 전달합니다.OpenAI의 채팅 모델을 사용하여 프롬프트에 따라 컨텍스트 인식 응답을 생성하는 체인을 구성합니다.
Atlas 보안 권장 사항에 대한 샘플 쿼리를 체인에 표시합니다.
LLM의 응답과 컨텍스트로 사용된 문서를 반환합니다.
// Implement RAG to answer questions on your data const retriever = vectorStore.asRetriever(); const prompt = PromptTemplate.fromTemplate(`Answer the question based on the following context: {context} Question: {question}`); const model = new ChatOpenAI({}); const chain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(), ]); // Prompt the LLM const question = "How can I secure my MongoDB Atlas cluster?"; const answer = await chain.invoke(question); console.log("Question: " + question); console.log("Answer: " + answer); // Return source documents const retrievedResults = await retriever.getRelevantDocuments(question) const documents = retrievedResults.map((documents => ({ pageContent: documents.pageContent, pageNumber: documents.metadata.loc.pageNumber, }))) console.log("\nSource documents:\n" + JSON.stringify(documents, 1, 2))
다음 명령을 실행하여 파일을 실행합니다.
파일을 저장한 후 다음 명령을 실행합니다. 생성된 응답은 다를 수 있습니다.
node get-started.js
Question: How can I secure my MongoDB Atlas cluster? Answer: The given context does not explicitly provide detailed steps to secure a MongoDB Atlas cluster. However, based on general best practices, here are some common steps to secure your MongoDB Atlas cluster: 1. **Enable Network Access Controls**: Configure IP whitelists to only allow connections from trusted IP addresses. 2. **Use Strong Authentication and Authorization**: Enable SCRAM (Salted Challenge Response Authentication Mechanism) for authenticating users and define roles with specific permissions. 3. **Encrypt Data**: Ensure data is encrypted both at rest and in transit by default in MongoDB Atlas. 4. **Enable VPC Peering (if applicable)**: Use Virtual Private Cloud (VPC) peering for secure and private connections. 5. **Monitor Activity**: Use MongoDB Atlas's built-in monitoring to track cluster activity and detect unauthorized attempts or anomalies. 6. **Implement Automated Backups**: Secure backups and ensure they are protected from unauthorized access. 7. **Educate Yourself**: Continuously refer to the MongoDB documentation and follow security best practices. It is recommended to visit the MongoDB documentation and security guides for the most accurate and detailed steps tailored to your specific use case. Source documents: [ { "pageContent": "Atlas free tier, or download MongoDB for local \ndevelopment.\nReview the MongoDB manuals and tutorials in our \ndocumentation. \nMore Resources\nFor more on getting started in MongoDB:", "pageNumber": 30 }, { "pageContent": "read isolation. \nWith MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \ntools like Atlas Charts can be configured to read from analytics nodes only.", "pageNumber": 21 }, { "pageContent": "• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\nGlobal Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or", "pageNumber": 27 }, { "pageContent": "22\nWorkload Type: Search\nIf your application requires rich full-text search functionality and you are running MongoDB on Atlas,", "pageNumber": 22 } ]
비동기 함수에 다음 코드를 추가하고 파일을 저장합니다.
이 코드는 다음을 수행합니다.
의미론적으로 유사한 문서를 쿼리 리트리버로 MongoDB Vector Search를 인스턴스화합니다. 또한 다음과 같은 선택적 매개변수도 지정합니다.
searchTypemmr로 지정하며, MongoDB Vector Search가 최대 한계 관련성(MMR)을 기반으로 문서를 검색하도록 지정합니다.filterlog.pageNumbers필드에 사전 필터를 추가하여 17페이지에만 표시되는 문서를 포함합니다.다음은 MMR 관련 매개변수입니다.
fetchKMMR 알고리즘에 문서를 전달하기 전에20개 문서만 가져옵니다.lambda0~1사이의 값을 사용하여 결과 간의 다양성 정도를 결정합니다. 여기서0은 최대 다양성을 나타내고1은 최소 다양성을 나타냅니다.
LLM이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시하는 LangChain 프롬프트 템플릿 을 정의합니다. LangChain은 이러한 문서를
{context}입력 변수에 전달하고 쿼리{question}변수에 전달합니다.OpenAI의 채팅 모델을 사용하여 프롬프트에 따라 컨텍스트 인식 응답을 생성하는 체인을 구성합니다.
Atlas 보안 권장 사항에 대한 샘플 쿼리를 체인에 표시합니다.
LLM의 응답과 컨텍스트로 사용된 문서를 반환합니다.
// Implement RAG to answer questions on your data const retriever = await vectorStore.asRetriever({ searchType: "mmr", // Defaults to "similarity filter: { preFilter: { "loc.pageNumber": { "$eq": 17 } } }, searchKwargs: { fetchK: 20, lambda: 0.1, }, }); const prompt = PromptTemplate.fromTemplate(`Answer the question based on the following context: {context} Question: {question}`); const model = new ChatOpenAI({}); const chain = RunnableSequence.from([ { context: retriever.pipe(formatDocumentsAsString), question: new RunnablePassthrough(), }, prompt, model, new StringOutputParser(), ]); // Prompt the LLM const question = "How can I secure my MongoDB Atlas cluster?"; const answer = await chain.invoke(question); console.log("Question: " + question); console.log("Answer: " + answer); // Return source documents const retrievedResults = await retriever.getRelevantDocuments(question) const documents = retrievedResults.map((documents => ({ pageContent: documents.pageContent, pageNumber: documents.metadata.loc.pageNumber, }))) console.log("\nSource documents:\n" + JSON.stringify(documents, 1, 2))
다음 명령을 실행하여 파일을 실행합니다.
파일을 저장한 후 다음 명령을 실행합니다. 생성된 응답은 다를 수 있습니다.
node get-started.js
Question: How can I secure my MongoDB Atlas cluster? Answer: To secure your MongoDB Atlas cluster, you can implement the following best practices: 1. **Enable Authentication and Authorization** Ensure that authentication is enabled, which is the default for MongoDB Atlas. Use role-based access control (RBAC) to grant users only the permissions they need. 2. **Use Strong Passwords or Authentication Mechanisms** Avoid simple passwords. Use strong, complex passwords for all database users. Alternatively, use certificate-based authentication or federated authentication with your identity provider. 3. **Whitelist IP Addresses** Configure your Access List (IP Whitelist) to restrict access to trusted IP addresses. This ensures that only specified IP addresses can connect to your cluster. 4. **Enable Network Encryption (TLS/SSL)** MongoDB Atlas supports TLS/SSL by default for securing data in transit. Ensure applications are configured to connect with SSL/TLS-enabled settings. 5. **Use End-to-End Encryption (Client-Side Field-Level Encryption)** Implement client-side field-level encryption to ensure sensitive fields are encrypted end-to-end. 6. **Regularly Rotate Authentication Credentials** Periodically rotate users' passwords or access keys to mitigate the risks of credential exposure. 7. **Use Private Networking** If supported, use Virtual Private Cloud (VPC) peering or private endpoints, such as AWS PrivateLink, to connect securely to your MongoDB Atlas cluster without using the public internet. 8. **Enable Database Auditing** Enable auditing to track database activity and detect potential anomalies or unauthorized access. 9. **Enable Backup and Data Recovery** Regularly back up your data using MongoDB Atlas' automated backup systems to ensure business continuity in case of accidental deletions or data loss. 10. **Keep the MongoDB Drivers Updated** Use the latest version of MongoDB drivers in your application to benefit from security updates and enhancements. 11. **Monitor and Set Alerts** Use MongoDB Atlas' monitoring tools to track metrics and set up alerts for suspicious activities or unusual resource consumption. 12. **Implement Application-Level Security** Ensure your application properly handles user authentication, session management, and input sanitization to prevent unauthorized access or injection attacks. 13. **Watch for Security Best Practices Updates** Regularly review MongoDB Atlas documentation and security advisories to stay aware of new features and recommendations. By following these practices, you can greatly enhance the security posture of your MongoDB Atlas cluster. Source documents: [ { "pageContent": "Optimizing Data \nAccess Patterns\nNative tools in MongoDB for improving query \nperformance and reducing overhead.", "pageNumber": 17 } ]
다음 단계
MongoDB Vector Search를 LangGraph와 통합하는 방법을 학습 MongoDB 와 LangGraph.js 통합을 참조하세요.
MongoDB는 다음과 같은 개발자 리소스도 제공합니다.