You can integrate MongoDB with LangChain to build generative AI and RAG applications. This page provides an overview of the LangChain MongoDB Python integration and the different components you can use in your applications.
Note
For a full list of components and methods, see API reference.
For the JavaScript integration, see LangChain JS/TS.
Installation and Setup
To use MongoDB Vector Search with LangChain, you must first install the langchain-mongodb package:
pip install langchain-mongodb
Vector Store
MongoDBAtlasVectorSearch is a vector store that allows you to store and retrieve vector embeddings from a collection in MongoDB. You can use this component to store embeddings from your data and retrieve them using MongoDB Vector Search.
This component requires an MongoDB Vector Search Index.
Usage
Atlas supports two embedding modes:
Manual embedding: Generate embedding vectors on the client's side with an embedding model you specify.
Automated embedding: MongoDB embeds text on the server's side without needing to generate them manually. To learn more, see Automated Embedding.
Parameter | Necessity | Description |
|---|---|---|
| Required | Specify the connection string for your MongoDB cluster. To learn more, see Connect to a Cluster via Client Libraries or Connection Strings. |
| Required | Specify the MongoDB namespace for which to store vector embeddings. For example, |
| Required | The embedding model to use. You can use any embedding model supported in LangChain or an |
| Optional | Name of the MongoDB Vector Search index. Defaults to |
| Optional | Field name that contains the document text content. Defaults to |
| Optional | Field name that stores the embedding vector. Defaults to |
| Optional | Similarity function to use. Accepted values are |
| Optional | Number of vector dimensions. If you set this value and you don't have a vector search index on the collection, MongoDB creates the index for you. |
| Optional | Flag that determines whether to automatically create the vector index if it doesn't exist. Defaults to |
| Optional | Timeout in seconds to wait for an auto-created vector search index to be ready. |
| Optional | A dictionary of additional options for configuring the vector search index. |
| Optional | Additional parameters to pass to the vector store such as LangChain-specific parameters. |
Retrievers
LangChain retrievers are components that you use to get relevant documents from your vector stores. You can use LangChain's built-in retrievers or the following MongoDB retrievers to query and retrieve data from MongoDB.
Vector Search Retriever
After instantiating MongoDB as a vector store, you can use the vector store instance as a retriever to query your data using MongoDB Vector Search.
Usage
from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch from langchain_voyageai import VoyageAIEmbeddings # Instantiate the vector store vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI namespace="<database-name>.<collection-name>", # Database and collection name embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use index_name="vector_index", # Name of the vector search index ) # 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)
Full-Text Retriever
MongoDBAtlasFullTextSearchRetriever is a retriever that performs full-text search by using MongoDB Search. Specifically, it uses Lucene's standard BM25 algorithm.
This retriever requires an MongoDB Search Index.
Usage
from langchain_mongodb.retrievers.full_text_search import ( MongoDBAtlasFullTextSearchRetriever, ) from pymongo import MongoClient # 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)
Note
Hybrid Search Retriever
MongoDBAtlasHybridSearchRetriever is a retriever that combines vector search and full-text search results by using the Reciprocal Rank Fusion (RRF) algorithm. To learn more, see How to Perform Hybrid Search.
This retriever requires an existing vector store, MongoDB Vector Search Index, and MongoDB Search Index.
Usage
from langchain_mongodb.retrievers.hybrid_search import ( MongoDBAtlasHybridSearchRetriever, ) from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch from langchain_voyageai import VoyageAIEmbeddings # Instantiate the vector store vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI namespace="<database-name>.<collection-name>", # Database and collection name embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use index_name="vector_index", # Name of the vector search index ) # 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)
Note
Parent Document Retriever
MongoDBAtlasParentDocumentRetriever is a retriever that queries smaller chunks first and then returns the larger parent document to the LLM. This type of retrieval is called parent document retrieval. Parent document retrieval can improve the responses of your RAG agents and applications by allowing for more granular searches on smaller chunks while giving LLMs the full context of the parent document.
This retriever stores both the parent and child documents in a single MongoDB collection, which supports efficient retrieval by only having to compute and index the child documents' embeddings.
Under the hood, this retriever creates the following:
An instance of MongoDBAtlasVectorSearch to handle vector search queries to the child documents.
An instance of MongoDBDocStore to handle storing and retrieving the parent documents.
Usage
Set text_key to page_content so that the vector store and the parent document store use the same field name for document text. Without this parameter, the retriever writes parent documents to one field and reads them from another, and queries fail with KeyError: 'text'.
from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetriever 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 model="voyage-3-large" ), 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 text_key="page_content", # Match the key the parent document store uses # 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)
Note
Self-Querying Retriever
MongoDBAtlasSelfQueryRetriever is a retriever that queries itself. The retriever uses an LLM to process your search query to identify possible metadata filters, forms a structured vector search query with the filters, and then runs the query to retrieve the most relevant documents.
For example, with a query like "What are thriller movies from after 2010 with ratings above 8?", the retriever can identify filters on the genre, year, and rating fields, and use those filters to retrieve documents that match the query.
This retriever requires an existing vector store and MongoDB Vector Search Index.
Usage
from langchain_mongodb.retrievers import MongoDBAtlasSelfQueryRetriever from langchain_mongodb import MongoDBAtlasVectorSearch from langchain_classic.chains.query_constructor.schema import AttributeInfo from langchain_voyageai import VoyageAIEmbeddings from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o", temperature=0) vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", namespace="langchain_db.movies", embedding=VoyageAIEmbeddings(model="voyage-3-large"), index_name="vector_index", ) # 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}}]}} documents = retriever.invoke("Movies made before 1960 that are rated higher than 8") print(documents)
Note
GraphRAG
GraphRAG is an alternative approach to traditional RAG that structures data as a knowledge graph of entities and their relationships instead of as vector embeddings. While vector-based RAG finds documents that are semantically similar to the query, GraphRAG finds connected entities to the query and traverses the relationships in the graph to retrieve relevant information.
This approach is particularly useful for answering relationship-based questions like "What is the connection between Company A and Company B?" or "Who is Person X's manager?".
MongoDBGraphStore is a component in the LangChain MongoDB integration that allows you to implement GraphRAG by storing entities (nodes) and their relationships (edges) in a MongoDB collection. This component stores each entity as a document with relationship fields that reference other documents in your collection. It executes queries using the $graphLookup aggregation stage.
Usage
from langchain_mongodb.graphrag import MongoDBGraphStore from langchain_openai import ChatOpenAI from langchain_core.documents import Document # 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 model="gpt-4o", temperature=0 ), # Other optional parameters... ) # Add documents to the graph docs = [ Document( page_content=( "MongoDB is a document database. " "Dev Ittycheria is the CEO of MongoDB." ) ), Document(page_content="MongoDB Atlas is the cloud platform offered by MongoDB."), ] graph_store.add_documents(docs) # Query the graph query = "Who is the CEO of MongoDB?" answer = graph_store.chat_response(query) print(answer.content)
Note
LLM Caches
Caches are used to optimize LLM performance by storing repetitive responses for similar or repetitive queries to avoid recomputing them. MongoDB provides the following caches for your LangChain applications.
MongoDB Cache
MongoDBCache allows you to store a basic cache in a MongoDB collection.
Usage
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="langchain_db", # Database to store the cache collection_name="cache", # Collection to store the cache ) )
Semantic Cache
Semantic caching is a more advanced form of caching that retrieves cached prompts based on the semantic similarity between the user input and cached results.
MongoDBAtlasSemanticCache is a semantic cache that uses MongoDB Vector Search to retrieve the cached prompts. This component requires an MongoDB Vector Search index.
Usage
from langchain_mongodb import MongoDBAtlasSemanticCache from langchain_core.globals import set_llm_cache from langchain_voyageai import VoyageAIEmbeddings set_llm_cache( MongoDBAtlasSemanticCache( embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model connection_string="<connection-string>", # MongoDB cluster URI database_name="langchain_db", # Database to store the cache collection_name="semantic_cache", # Collection to store the cache ) )
DeepAgents Virtual File System
LangChain DeepAgents is an agent harness designed for long-running, multi-step tasks. It handles planning, context management, and delegating work to sub-agents. The harness supports a swappable backend protocol that lets you change where an agent's files actually live. The langchain-mongodb-deepagents-vfs package is an implementation of that protocol: Amazon S3 holds the files, an embedding provider (AWS Bedrock or OpenAI) computes embeddings, MongoDB Atlas holds the chunks and embeddings, and the MongoFilesystemBackend class routes each file operation to the correct handler.
Use this package when your agent needs to search a large set of existing files in S3. grep runs as a single MongoDB aggregation that combines full-text and vector search results using the Reciprocal Rank Fusion (RRF) algorithm, so it scales without loading every file into your agent to filter them one by one. glob and ls handle filename and directory lookups directly. When an agent calls read, write, edit, upload_files, or download_files, those calls go directly to S3, where your files live. Files added by other tools are automatically picked up and indexed by the backend's watcher.
Before you install the package, make sure you have:
A MongoDB Atlas connection string
AWS credentials (
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_DEFAULT_REGION), with an IAM policy granting:s3:GetObject,s3:PutObject,s3:ListBucket, ands3:DeleteObjecton your S3 bucketbedrock:InvokeModelonamazon.titan-embed-text-v2:0, in the same region asAWS_DEFAULT_REGION, needed if you use the default Bedrock provider
Your choice of embedding provider: Bedrock (the default, uses the AWS credentials above) or OpenAI (set
EMBEDDING_PROVIDER=openaiand provide anOPENAI_API_KEY)
To install the package, determine whether you want MongoDB to generate search embeddings by using AWS Bedrock or OpenAI, and run the matching command:
pip install "langchain-mongodb-deepagents-vfs[bedrock]"
pip install "langchain-mongodb-deepagents-vfs[openai]"
Usage
Instantiate MongoFilesystemBackend with your S3 bucket name and Atlas connection string. The following example writes two files to S3, then demonstrates each search method:
grepsearches the file's contentglobmatches file paths by patternlslists a directory's contents
from langchain_mongodb_deepagents_vfs import MongoFilesystemBackend # Instantiate the backend backend = MongoFilesystemBackend( s3_bucket_name="<bucket-name>", # S3 bucket that stores your files mongodb_connection_string="<connection-string>", # MongoDB Atlas connection string ) # Write two files to S3: one .txt, one .md, so glob can demonstrate # filtering by extension backend.write("mongodb_vfs/docs/notes.txt", "Our authentication flow uses OAuth 2.0.") backend.write("mongodb_vfs/docs/overview.md", "This directory contains onboarding docs.") # Search for files that mention "authentication flow" # Newly written files can take a few seconds to become searchable result = backend.grep("authentication flow", path="mongodb_vfs/docs/") print("grep matches:") for match in result.matches or []: print(match["path"], match["line"], match["text"]) # Find files that match a glob pattern result = backend.glob("*.txt", path="mongodb_vfs/docs/") print("glob matches:", result.matches) # List the contents of a directory result = backend.ls("mongodb_vfs/docs/") print("ls entries:", result.entries) print("init_errors:", backend.init_errors)
By default, the backend restricts every operation to the mongodb_vfs/ prefix in your bucket. Pass a different s3_prefix value to MongoFilesystemBackend to change this, or s3_prefix="" for whole-bucket access.
Note
To learn how to connect this backend to a DeepAgents agent, see the DeepAgents Quickstart.
MongoDB Agent Toolkit
The MongoDB Agent Toolkit is a collection of tools that you can pass to a LangGraph ReAct Agent so that it can interact with your MongoDB resources.
Available Tools
Name | Description |
|---|---|
| A tool for querying a MongoDB database. |
| A tool for getting metadata about a MongoDB database. |
| A tool for getting a MongoDB database's collection names. |
| A tool that calls an LLM to check if a database query is correct. |
Usage
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="<database-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(), prompt=system_message) agent.step_timeout = 60 events = agent.stream( {"messages": [("user", test_query)]}, stream_mode="values", ) messages = [] for event in events: messages.extend(event["messages"]) print(messages[-1].content)
Note
Document Loader
Document loaders are tools that help you to load data for your LangChain applications.
MongoDBLoader is a document loader that returns a list of documents from a MongoDB database.
Usage
from langchain_mongodb.loaders import MongoDBLoader loader = MongoDBLoader.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI db_name="langchain_db", # Database that contains the collection collection_name="documents", # Collection to load documents from filter_criteria={"category": "ai"}, # Optional document to specify a filter field_names=["title", "summary"], # Optional list of fields to include metadata_names=["category"], # Optional metadata fields to extract ) docs = loader.load()
Note
Chat History
MongoDBChatMessageHistory is a component that allows you to store and manage chat message histories in a MongoDB database. It can save both user and AI-generated messages associated with a unique session identifier. Use this component for applications that track interactions over time, such as chatbots.
Usage
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="langchain_db", # Database to store the chat history collection_name="chat_history", # Collection to store the chat history ) chat_message_history.add_user_message("Hello") chat_message_history.add_ai_message("Hi")
print(chat_message_history.messages)
[HumanMessage(content='Hello', additional_kwargs={}, response_metadata={}), AIMessage(content='Hi', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[])]
Storage
You can use the following custom data stores to manage and store data in MongoDB.
Document Store
MongoDBDocStore is a custom key-value store that uses MongoDB to store and manage documents. You can perform CRUD operations as you would on any other MongoDB collection.
Usage
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)
Note
Binary Storage
MongoDBByteStore is a custom datastore that uses MongoDB to store and manage binary data, specifically data represented in bytes. You can perform CRUD operations with key-value pairs where the keys are strings and the values are byte sequences.
Usage
from langchain_community.storage.mongodb import MongoDBByteStore # Instantiate the MongoDBByteStore mongodb_store = MongoDBByteStore( connection_string="<connection-string>", # MongoDB cluster URI db_name="langchain_db", # Name of the database collection_name="byte_store", # 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) # Iterate over keys for key in mongodb_store.yield_keys(): print(key) # Delete keys mongodb_store.mdelete(["key1", "key2"])
[b'hello', b'world'] key1 key2
Note
Additional Resources
To learn how to integrate MongoDB with LangGraph, see Integrate MongoDB with LangGraph.
For interactive Python notebooks, see Docs Notebooks Repository and Generative AI Use Cases Repository.