For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Integrate MongoDB with LangChain

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.

Get Started

Note

For a full list of components and methods, see API reference.

For the JavaScript integration, see LangChain JS/TS.

To use MongoDB Vector Search with LangChain, you must first install the langchain-mongodb package:

pip install langchain-mongodb

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.

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.

The quickest way to instantiate your vector store is to use the connection string for your MongoDB cluster or local deployment:

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(model="voyage-3-large"), # Embedding model to use
index_name="vector_index", # Name of the vector search index
# Other optional parameters...
)

To use automated embedding, pass an AutoEmbeddings instance to the embedding parameter. This enables MongoDB to generate and manage embedding vectors automatically.

With automated embedding:

  • No client-side embedding computation is required

  • Raw text is sent directly to MongoDB

  • Embedding vectors are generated server-side

  • The embedding_key field is not stored in documents

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_mongodb.embeddings import AutoEmbeddings
from langchain_core.documents import Document
# Some documents to embed
docs = [
Document(page_content="foo", metadata={"baz": "bar"}),
Document(page_content="thud", metadata={"bar": "baz"}),
]
# Instantiate the vector store with Automated Embedding
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string="<connection-string>", # MongoDB cluster URI
namespace="<database-name>.<collection-name>", # Database and collection name
embedding=AutoEmbeddings(model="voyage-4"), # Enable Automated Embedding
index_name="vector_index", # Name of the vector search index
# Other optional parameters...
)
# Add documents - text is embedded server-side
vector_store.add_documents(documents=docs)
# Search - queries are embedded server-side
results = vector_store.similarity_search("search query")

The integration also supports other methods of instantiating the vector store:

  • Using the MongoDB client:

    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(model="voyage-3-large"), # Embedding model to use
    index_name="vector_index", # Name of the vector search index
    # Other optional parameters...
    )
  • From documents that you've created:

    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(model="voyage-3-large"), # Embedding model to use
    collection=collection, # Collection to store embeddings
    index_name="vector_index", # Name of the vector search index
    )

Use the following parameters to configure the vector store.

Parameter
Necessity
Description

connection_string

Required

Specify the connection string for your MongoDB cluster. To learn more, see Connect to a Cluster via Client Libraries or Connection Strings.

namespace

Required

Specify the MongoDB namespace for which to store vector embeddings.

For example, langchain_db.test.

embedding

Required

The embedding model to use. You can use any embedding model supported in LangChain or an AutoEmbeddings instance for server-side Automated Embedding.

index_name

Optional

Name of the MongoDB Vector Search index. Defaults to vector_index.

text_key

Optional

Field name that contains the document text content. Defaults to text.

embedding_key

Optional

Field name that stores the embedding vector. Defaults to embedding.

relevance_score_fn

Optional

Similarity function to use. Accepted values are cosine, euclidean, or dotProduct. Defaults to cosine.

dimensions

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.

auto_create_index

Optional

Flag that determines whether to automatically create the vector index if it doesn't exist. Defaults to False.

auto_index_timeout

Optional

Timeout in seconds to wait for an auto-created vector search index to be ready.

vector_index_options

Optional

A dictionary of additional options for configuring the vector search index.

**kwargs

Optional

Additional parameters to pass to the vector store such as LangChain-specific parameters.

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.

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.

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)

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.

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)

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.

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)

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:

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)

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.

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)

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.

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)

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.

MongoDBCache allows you to store a basic cache in a MongoDB collection.

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 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.

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
)
)

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, and s3:DeleteObject on your S3 bucket

    • bedrock:InvokeModel on amazon.titan-embed-text-v2:0, in the same region as AWS_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=openai and provide an OPENAI_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]"

Instantiate MongoFilesystemBackend with your S3 bucket name and Atlas connection string. The following example writes two files to S3, then demonstrates each search method:

  • grep searches the file's content

  • glob matches file paths by pattern

  • ls lists 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.

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.

Name
Description

MongoDBDatabaseToolkit

A tool for querying a MongoDB database.

InfoMongoDBDatabaseTool

A tool for getting metadata about a MongoDB database.

ListMongoDBDatabaseTool

A tool for getting a MongoDB database's collection names.

QueryMongoDBCheckerTool

A tool that calls an LLM to check if a database query is correct.

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)

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.

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()

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.

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=[])]

You can use the following custom data stores to manage and store data in MongoDB.

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.

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 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.

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

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.