Docs Menu
Docs Home
/
Atlas
/ /

MongoDB 와 LangChain 통합

MongoDB Vector Search를 LangChain과 통합하여 생성형 AI 및 RAG 애플리케이션을 빌드 할 수 있습니다. 이 페이지에서는 LangChain MongoDB Python 통합에 대한 개요와 애플리케이션에서 사용할 수 있는 다양한 구성 요소를 제공합니다.

시작하기

참고

구성 요소 및 메서드의 전체 목록은 API 참조를참조하세요.

JavaScript 통합에 대해서는 LangChain JS/TS를 참조하세요.

LangChain과 함께 MongoDB Vector Search를 사용하려면 먼저 langchain-mongodb 패키지 설치해야 합니다.

pip install langchain-mongodb

MongoDBAtlasVectorSearch 는 MongoDB 의 컬렉션 에서 벡터 임베딩을 저장 하고 조회 할 수 있는 벡터 저장 입니다. 이 구성 요소를 사용하여 데이터의 임베딩을 저장 하고 MongoDB Vector Search를 사용하여 조회 .

이 구성 요소에는 MongoDB Vector Search 인덱스가 필요합니다.

벡터 저장 인스턴스화하는 가장 빠른 방법은 MongoDB cluster 또는 로컬 배포서버 에 연결 문자열 사용하는 것입니다.

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_voyageai import VoyageAIEmbeddings
# Instantiate the vector store using your MongoDB connection string
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string = "<connection-string>", # MongoDB cluster URI
namespace = "<database-name>.<collection-name>", # Database and collection name
embedding = VoyageAIEmbeddings(), # Embedding model to use
index_name = "vector_index", # Name of the vector search index
# Other optional parameters...
)

통합은 벡터 저장소를 인스턴스화하는 다른 방법도 지원합니다.

  • MongoDB 클라이언트를 사용하여 다음을 수행합니다.

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from pymongo import MongoClient
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Instantiate the vector store
    vector_store = MongoDBAtlasVectorSearch(
    collection = collection, # Collection to store embeddings
    embedding = VoyageAIEmbeddings(), # Embedding model to use
    index_name = "vector_index" # Name of the vector search index
    # Other optional parameters...
    )
  • 사용자가 만든 문서에서:

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from langchain_core.documents import Document
    from pymongo import MongoClient
    # Some documents to embed
    document_1 = Document(page_content="foo", metadata={"baz": "bar"})
    document_2 = Document(page_content="thud", metadata={"bar": "baz"})
    docs = [ document_1, document_2 ]
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Create the vector store from documents
    vector_store = MongoDBAtlasVectorSearch.from_documents(
    documents = docs, # List of documents to embed
    embedding = VoyageAIEmbeddings(), # Embedding model to use
    collection = collection, # Collection to store embeddings
    index_name = "vector_index" # Name of the vector search index
    # Other optional parameters...
    )

LangChain 리트리버 는 벡터 저장소에서 관련 문서를 가져오는 데 사용하는 구성 요소입니다. LangChain의 내장 리트리버 또는 다음과 같은 MongoDB 리트리버를 사용하여 MongoDB 에서 데이터를 쿼리 하고 조회 수 있습니다.

MongoDB 벡터 저장 로 인스턴스화한 후 벡터 저장 인스턴스 리트리버로 사용하여 MongoDB Vector Search를 사용하여 데이터를 쿼리 수 있습니다.

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
# Instantiate the vector store
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
# Vector store arguments...
)
# Use the vector store as a retriever
retriever = vector_store.as_retriever()
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasFullTextSearchRetriever MongoDB Search를 사용하여 전체 텍스트 검색 수행하는 리트리버입니다. 특히 Lucene의 표준 BM25 알고리즘사용합니다.

이 리트리버에는 MongoDB 검색 인덱스가 필요합니다.

from langchain_mongodb.retrievers.full_text_search import MongoDBAtlasFullTextSearchRetriever
# Connect to your MongoDB cluster
client = MongoClient("<connection-string>")
collection = client["<database-name>"]["<collection-name>"]
# Initialize the retriever
retriever = MongoDBAtlasFullTextSearchRetriever(
collection = collection, # MongoDB Collection in Atlas
search_field = "<field-name>", # Name of the field to search
search_index_name = "<index-name>" # Name of the search index
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasHybridSearchRetriever RRF(Reciprocal Rank Fusion) 알고리즘을 사용하여 벡터 검색과 전체 텍스트 검색 결과를 결합하는 검색기입니다. 자세한 내용은 하이브리드 검색 수행 방법을 참조하세요.

이 리트리버에는 기존 벡터 저장, MongoDB 벡터 검색 인덱스MongoDB 검색 인덱스가 필요합니다.

from langchain_mongodb.retrievers.hybrid_search import MongoDBAtlasHybridSearchRetriever
# Initialize the retriever
retriever = MongoDBAtlasHybridSearchRetriever(
vectorstore = <vector-store>, # Vector store instance
search_index_name = "<index-name>", # Name of the MongoDB Search index
top_k = 5, # Number of documents to return
fulltext_penalty = 60.0, # Penalty for full-text search
vector_penalty = 60.0 # Penalty for vector search
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasParentDocumentRetriever 작은 청크를 먼저 쿼리한 다음 큰 상위 문서를 LLM에 반환하는 검색기입니다. 이러한 유형의 검색을 상위 문서 검색이라고 합니다. 상위 문서 검색은 작은 청크에 대한 더 세분화된 검색을 허용하면서 LLM에 상위 문서의 전체 컨텍스트를 제공함으로써 RAG 에이전트 및 애플리케이션의 응답을 개선할 수 있습니다.

검색기는 상위 및 하위 문서를 단일 MongoDB 컬렉션에 저장하며 하위 문서의 임베딩만 계산하고 인덱싱함으로써 효율적인 검색을 지원합니다.

이 검색기는 내부적으로 다음을 생성합니다.

  • 하위 문서에 대한 벡터 검색 쿼리를 처리하기 위한 MongoDBAtlasVectorSearch의 인스턴스입니다.

  • 상위 문서의 저장 및 검색을 처리하기 위한 MongoDBDocStore의 인스턴스입니다.

from langchain_mongodb.retrievers.parent_document import ParentDocumentRetriever
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_voyageai import VoyageAIEmbeddings
retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string(
connection_string = <connection-string>, # MongoDB cluster URI
embedding_model = VoyageAIEmbeddings(), # Embedding model to use
child_splitter = RecursiveCharacterTextSplitter(), # Text splitter to use
database_name = <database-name>, # Database to store the collection
collection_name = <collection-name>, # Collection to store the collection
# Additional vector store or parent class arguments...
)
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasSelfQueryRetriever 자체 쿼리를 수행하는 리트리버입니다. 리트리버는 LLM을 사용하여 검색 쿼리 프로세스 사용 가능한 메타데이터 필터를 식별하고, 필터를 사용하여 구조화된 벡터 검색 쿼리 구성한 다음, 쿼리 실행하여 가장 관련성이 높은 문서를 조회 .

예시 들어 8 이상의 평점이 있는 2010 이후의 스릴러 영화는 무엇인가요?"와 같은 쿼리 사용하여 리트리버는 genre, yearrating 필드에서 필터를 식별하고 해당 필터를 사용할 수 있습니다. 필터를 사용하여 쿼리 와 일치하는 문서를 조회 .

이 리트리버에는 기존 벡터 저장MongoDB Vector Search 인덱스가 필요합니다.

from langchain_mongodb.retrievers import MongoDBAtlasSelfQueryRetriever
from langchain_mongodb import MongoDBAtlasVectorSearch
# Given an existing vector store with movies data, define metadata describing the data
metadata_field_info = [
AttributeInfo(
name="genre",
description="The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'animated']",
type="string",
),
AttributeInfo(
name="year",
description="The year the movie was released",
type="integer",
),
AttributeInfo(
name="rating", description="A 1-10 rating for the movie", type="float"
),
]
# Create the retriever from the VectorStore, an LLM and info about the documents
retriever = MongoDBAtlasSelfQueryRetriever.from_llm(
llm=llm,
vectorstore=vector_store,
metadata_field_info=metadata_field_info,
document_contents="Descriptions of movies",
enable_limit=True
)
# This example results in the following composite filter sent to $vectorSearch:
# {'filter': {'$and': [{'year': {'$lt': 1960}}, {'rating': {'$gt': 8}}]}}
print(retriever.invoke("Movies made before 1960 that are rated higher than 8"))

GraphRAG는 데이터를 벡터 임베딩 대신 엔터티와 이들 간의 관계로 구성된 지식 그래프로 구조화하는 기존 RAG의 대안적 접근 방식입니다 벡터 기반 RAG는 쿼리와 의미적으로 유사한 문서를 찾는 반면, GraphRAG는 쿼리와 연결된 엔터티를 찾아 그래프의 관계를 탐색하여 관련 정보를 조회합니다.

이 접근 방식은 '회사 A와 회사 B의 관계는 무엇인가?' 또는 '사람 X의 관리자는 누구인가?'와 같은 관계 기반 질문에 답하는 데 특히 유용합니다.

MongoDBGraphStore 는 LangChain MongoDB 통합의 구성 요소로, 엔터티(노드)와 그 관계(엣지)를 MongoDB 컬렉션에 저장하여 GraphRAG를 구현할 수 있습니다. 이 구성 요소는 각 엔터티를 컬렉션 내 다른 문서를 참조하는 관계 필드가 포함된 문서로 저장합니다. $graphLookup 집계 단계를 사용하여 쿼리를 실행합니다.

from langchain_mongodb import MongoDBGraphStore
from langchain_openai import ChatOpenAI
# Initialize the graph store
graph_store = MongoDBGraphStore(
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the graph
collection_name = "<collection-name>", # Collection to store the graph
entity_extraction_model = ChatOpenAI(), # LLM to extract entities from documents (e.g. OpenAI model)
# Other optional parameters...
)
# Add documents to the graph
docs = [...] # Your documents
graph_store.add_documents(docs)
# Query the graph
query = "Who is the CEO of MongoDB?"
answer = graph_store.chat_response(query)
print(answer.content)

캐시 는 유사하거나 반복적인 쿼리에 대한 반복적인 응답을 저장하여 다시 계산하지 않도록 함으로써 LLM 성능을 최적화하는 데 사용됩니다. MongoDB LangChain 애플리케이션을 위해 다음과 같은 캐시를 제공합니다.

MongoDBCache MongoDB 컬렉션 에 기본 캐시 저장 수 있습니다.

from langchain_mongodb import MongoDBCache
from langchain_core.globals import set_llm_cache
set_llm_cache(MongoDBCache(
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the cache
collection_name = "<collection-name>" # Collection to store the cache
))

시맨틱 캐싱은 사용자 입력과 캐시된 결과 간의 시맨틱 유사성을 기반으로 캐시된 프롬프트를 조회하는 발전된 형태의 캐싱입니다.

MongoDBAtlasSemanticCache MongoDB Vector Search를 사용하여 캐시된 프롬프트를 조회 시맨틱 캐시 입니다. 이 구성 요소에는 MongoDB Vector Search 인덱스필요합니다.

from langchain_mongodb import MongoDBAtlasSemanticCache
from langchain_core.globals import set_llm_cache
from langchain_voyageai import VoyageAIEmbeddings
set_llm_cache(MongoDBAtlasSemanticCache(
embedding = VoyageAIEmbeddings(), # Embedding model to use
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the cache
collection_name = "<collection-name>" # Collection to store the cache
))

MongoDB Agent 툴킷은 MongoDB 리소스와 상호 작용 수 있도록 LangGraph React Agent에 전달할 수 있는 연장 컬렉션 입니다.

이름
설명

MongoDBDatabaseToolkit

MongoDB database 쿼리하기 위한 도구입니다.

InfoMongoDBDatabaseTool

MongoDB database 에 대한 메타데이터 가져오는 도구입니다.

ListMongoDBDatabaseTool

MongoDB 데이터베이스의 컬렉션 이름을 가져오는 도구입니다.

QueryMongoDBCheckerTool

데이터베이스 쿼리 올바른지 확인하기 위해 LLM을 호출하는 도구입니다.

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langchain_mongodb.agent_toolkit import (
MONGODB_AGENT_SYSTEM_PROMPT,
MongoDBDatabase,
MongoDBDatabaseToolkit,
)
db_wrapper = MongoDBDatabase.from_connection_string(
CONNECTION_STRING, database=DB_NAME
)
llm = ChatOpenAI(model="gpt-4o-mini", timeout=60)
toolkit = MongoDBDatabaseToolkit(db=db_wrapper, llm=llm)
system_message = MONGODB_AGENT_SYSTEM_PROMPT.format(top_k=5)
test_query = "Which country's customers spent the most?"
agent = create_react_agent(llm, toolkit.get_tools(), state_modifier=system_message)
agent.step_timeout = 60
events = agent.stream(
{"messages": [("user", test_query)]},
stream_mode="values",
)
messages = []

문서 로더 는 LangChain 애플리케이션의 데이터를 로드하는 데 도움이 되는 도구입니다.

MongoDBLoader MongoDB 데이터베이스에서 문서 목록을 반환하는 문서 로더입니다.

from langchain_mongodb.loaders import MongoDBLoader
loader = MongoDBLoader.from_connection_string(
connection_string = "<connection-string>", # MongoDB cluster URI
db_name = "<database-name>", # Database that contains the collection
collection_name = "<collection-name>", # Collection to load documents from
filter_criteria = { "field": "value" }, # Optional document to specify a filter
field_names = ["<field-name>", "..." ], # Optional list of fields to include in document content
metadata_names = ["<metadata-field>", "..."] # Optional metadata fields to extract
)
docs = loader.load()

MongoDBChatMessageHistory MongoDB 데이터베이스에서 채팅 메시지 기록을 저장하고 관리할 수 있는 구성 요소입니다. 고유 세션 식별자와 연결된 사용자 메시지와 AI가 생성한 메시지를 모두 저장할 수 있습니다. 챗봇과 같이 시간 경과에 따른 상호 작용을 추적해야 하는 애플리케이션에 유용합니다.

from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
chat_message_history = MongoDBChatMessageHistory(
session_id = "<session-id>", # Unique session identifier
connection_string = "<connection-string>", # MongoDB cluster URI
database_name = "<database-name>", # Database to store the chat history
collection_name = "<collection-name>" # Collection to store the chat history
)
chat_message_history.add_user_message("Hello")
chat_message_history.add_ai_message("Hi")
chat_message_history.messages
[HumanMessage(content='Hello'), AIMessage(content='Hi')]

MongoDB에서 데이터를 관리하고 저장하기 위해 다음과 같은 사용자 지정 데이터 저장소를 사용할 수 있습니다.

MongoDBDocStore 는 MongoDB를 사용하여 문서를 저장하고 관리하는 맞춤형 키-값 저장소입니다. 다른 MongoDB 컬렉션과 마찬가지로 CRUD 작업을 수행할 수 있습니다.

from pymongo import MongoClient
from langchain_mongodb.docstores import MongoDBDocStore
# Replace with your MongoDB connection string and namespace
connection_string = "<connection-string>"
namespace = "<database-name>.<collection-name>"
# Initialize the MongoDBDocStore
docstore = MongoDBDocStore.from_connection_string(connection_string, namespace)

MongoDBByteStore 바이너리 데이터, 특히 바이트로 표시되는 데이터를 MongoDB를 사용하여 저장하고 관리하는 사용자 지정 데이터스토어입니다. 키가 문자열이고 값이 바이트 시퀀스인 키-값 쌍을 사용하여 CRUD 작업을 수행할 수 있습니다.

from langchain.storage import MongoDBByteStore
# Instantiate the MongoDBByteStore
mongodb_store = MongoDBByteStore(
connection_string = "<connection-string>", # MongoDB cluster URI
db_name = "<database-name>", # Name of the database
collection_name = "<collection-name>" # Name of the collection
)
# Set values for keys
mongodb_store.mset([("key1", b"hello"), ("key2", b"world")])
# Get values for keys
values = mongodb_store.mget(["key1", "key2"])
print(values) # Output: [b'hello', b'world']
# Iterate over keys
for key in mongodb_store.yield_keys():
print(key) # Output: key1, key2
# Delete keys
mongodb_store.mdelete(["key1", "key2"])

MongoDB Vector Search를 LangGraph와 통합하는 방법을 학습하려면 MongoDB 와 LangGraph 통합하기를 참조하세요.

대화형 Python 노트북에 대해서는 Docs 노트북 리포지토리생성형 AI 사용 사례 리포지토리를 참조하세요.

돌아가기

AI 통합

스킬 배지 획득

무료로 'MongoDB를 사용한 RAG'를 마스터하세요!

자세한 내용을 알아보세요.

이 페이지의 내용