> This page location: /docs.md > /docs/development.md > /docs/atlas/ai-integrations.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: uri, auto-embed, other
-->

# Integrate MongoDB with LangChain

You can integrate MongoDB with LangChain to build generative AI and RAG (Retrieval-Augmented Generation) 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.](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/api_docs.html)

For the JavaScript integration, see [LangChain JS/TS.](https://www.mongodb.com/docs/atlas/ai-integrations/langchain-js.md#std-label-langchain-js)

## Installation and Setup

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

```shell
pip install langchain-mongodb
```

## Vector Store

`MongoDBAtlasVectorSearch` is a [vector store](https://python.langchain.com/docs/how_to/#vector-stores) 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.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector-search)

### 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.](https://www.mongodb.com/docs/vector-search/crud-embeddings/automated-embedding.md#std-label-avs-auto-embeddings)

### Manual Embedding

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

```python
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...
)

```

#### Options

##### 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](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver) or [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string/) |
| `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](https://python.langchain.com/docs/integrations/text_embedding/) 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. |

**Note:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/get-started.md#std-label-langchain-get-started)

- [Video](https://www.youtube.com/watch?v=ZvwUzcMvKiI)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/vectorstores/langchain_mongodb.vectorstores.MongoDBAtlasVectorSearch.html)

- [LangChain Documentation](https://python.langchain.com/docs/integrations/vectorstores/mongodb_atlas)

## Retrievers

LangChain [retrievers](https://python.langchain.com/docs/concepts/#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](https://www.mongodb.com/docs/atlas/ai-integrations/langchain.md#std-label-langchain-vector-store), you can use the vector store instance as a retriever to query your data using [MongoDB Vector Search.](https://www.mongodb.com/docs/vector-search.md#std-label-avs-overview)

#### Usage

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

```

**Note:**

- [RAG Usage Example](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/get-started.md#std-label-langchain-rag)

- [LangGraph Usage Example](https://www.mongodb.com/docs/atlas/ai-integrations/langgraph.md#std-label-langgraph-retrieval)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/vectorstores/langchain_mongodb.vectorstores.MongoDBAtlasVectorSearch.html#langchain_mongodb.vectorstores.MongoDBAtlasVectorSearch.as_retriever)

### Full-Text Retriever

`MongoDBAtlasFullTextSearchRetriever` is a retriever that performs full-text search by using [MongoDB Search](https://www.mongodb.com/docs/search.md#std-label-fts-top-ref). Specifically, it uses Lucene's standard [BM25 algorithm.](https://en.wikipedia.org/wiki/Okapi_BM25)

This retriever requires an [MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-ref-create-index)

#### Usage

```python
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:**

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/retrievers/langchain_mongodb.retrievers.full_text_search.MongoDBAtlasFullTextSearchRetriever.html)

### 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.](https://www.mongodb.com/docs/search/tutorial/hybrid-search.md#std-label-as_hybrid-search)

This retriever requires an existing [vector store](https://www.mongodb.com/docs/atlas/ai-integrations/langchain.md#std-label-langchain-vector-store), [MongoDB Vector Search Index](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector-search), and [MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-ref-create-index)

#### Usage

```python
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:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/hybrid-search.md#std-label-langchain-hybrid-search)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/retrievers/langchain_mongodb.retrievers.hybrid_search.MongoDBAtlasHybridSearchRetriever.html)

### Parent Document Retriever

`MongoDBAtlasParentDocumentRetriever` is a retriever that queries smaller chunks first and then returns the larger parent document to the LLM (Large Language Model). 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 LLM (Large Language Model)s 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](https://www.mongodb.com/docs/atlas/ai-integrations/langchain.md#std-label-langchain-vector-store) to handle vector search queries to the child documents.

- An instance of [MongoDBDocStore](https://www.mongodb.com/docs/atlas/ai-integrations/langchain.md#std-label-langchain-document-store) 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'`.

```python
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:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/parent-document-retrieval.md#std-label-langchain-parent-document)

- [Video](https://www.youtube.com/watch?v=v5V3W-NNSQw)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/retrievers/langchain_mongodb.retrievers.parent_document.MongoDBAtlasParentDocumentRetriever.html)

### 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](https://www.mongodb.com/docs/atlas/ai-integrations/langchain.md#std-label-langchain-vector-store) and [MongoDB Vector Search Index.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector-search)

#### Usage

```python
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:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/self-query-retrieval.md#std-label-langchain-self-query)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/retrievers/langchain_mongodb.retrievers.self_querying.MongoDBAtlasSelfQueryRetriever.html)

## GraphRAG

[GraphRAG](https://microsoft.github.io/graphrag/) is an alternative approach to traditional [RAG](https://www.mongodb.com/docs/vector-search/tutorials/rag.md#std-label-avs-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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup.md#mongodb-pipeline-pipe.-graphLookup) aggregation stage.

### Usage

```python
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:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/graph-rag.md#std-label-langchain-graph-rag)

- [Video](https://www.youtube.com/watch?v=LHzOkwdRars)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/graphrag/langchain_mongodb.graphrag.graph.MongoDBGraphStore.html)

## LLM Caches

[Caches](https://python.langchain.com/docs/how_to/caching_embeddings/) 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

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

```

**Note:**

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/cache/langchain_mongodb.cache.MongoDBCache.html)

- [LangChain Documentation](https://python.langchain.com/docs/integrations/providers/mongodb_atlas/#mongodbcache)

### 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.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector-search)

#### Usage

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

```

**Note:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/memory-semantic-cache.md#std-label-langchain-memory)

- [Video](https://www.youtube.com/watch?v=kAgSPzlgnDM)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/cache/langchain_mongodb.cache.MongoDBAtlasSemanticCache.html)

- [LangChain Documentation](https://python.langchain.com/docs/integrations/providers/mongodb_atlas/#mongodbatlassemanticcache)

## DeepAgents Virtual File System

[LangChain DeepAgents](https://github.com/langchain-ai/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:

```python
pip install "langchain-mongodb-deepagents-vfs[bedrock]"
```

```python
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:

- `grep` searches the file's content

- `glob` matches file paths by pattern

- `ls` lists a directory's contents

```python
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.](https://docs.langchain.com/oss/deepagents/code/quickstart)

## MongoDB Agent Toolkit

The [MongoDB Agent Toolkit](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/agent_toolkit/langchain_mongodb.agent_toolkit.toolkit.MongoDBDatabaseToolkit.html#langchain_mongodb.agent_toolkit.toolkit.MongoDBDatabaseToolkit) is a collection of tools that you can pass to a [LangGraph ReAct Agent](https://python.langchain.com/api_reference/langchain/agents/langchain.agents.react.agent.create_react_agent.html) so that it can interact with your MongoDB resources.

### Available Tools

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

#### Usage

```python
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:**

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/agent_toolkit/langchain_mongodb.agent_toolkit.toolkit.MongoDBDatabaseToolkit.html#langchain_mongodb.agent_toolkit.toolkit.MongoDBDatabaseToolkit)

## Document Loader

[Document loaders](https://python.langchain.com/docs/how_to/#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

```python
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:**

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/loaders/langchain_mongodb.loaders.MongoDBLoader.html)

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

```python
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")

```

```python
print(chat_message_history.messages)

```

**Output:**

```python
[HumanMessage(content='Hello', additional_kwargs={}, response_metadata={}), AIMessage(content='Hi', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[])]

```

**Note:**

- [Tutorial](https://www.mongodb.com/docs/atlas/ai-integrations/langchain/memory-semantic-cache.md#std-label-langchain-memory)

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/chat_message_histories/langchain_mongodb.chat_message_histories.MongoDBChatMessageHistory.html)

- [LangChain Documentation](https://python.langchain.com/docs/integrations/memory/mongodb_chat_message_history/)

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

```python
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:**

- [API Reference](https://langchain-mongodb.readthedocs.io/en/latest/langchain_mongodb/docstores/langchain_mongodb.docstores.MongoDBDocStore.html#langchain_mongodb.docstores.MongoDBDocStore)

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

```python
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"])

```

**Output:**

```python
[b'hello', b'world']
key1
key2

```

**Note:**

- [API Reference](https://api.python.langchain.com/en/latest/community/storage/langchain_community.storage.mongodb.MongoDBByteStore.html)

## Additional Resources

To learn how to integrate MongoDB with LangGraph, see [Integrate MongoDB with LangGraph.](https://www.mongodb.com/docs/atlas/ai-integrations/langgraph.md#std-label-langgraph)

For interactive Python notebooks, see [Docs Notebooks Repository](https://github.com//mongodb/docs-notebooks/blob/main/ai-integrations) and [Generative AI Use Cases Repository.](https://github.com//mongodb-developer/GenAI-Showcase/tree/main)
