> ## Documentation Index
> Fetch the complete documentation index at: https://docs.langchain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Long-term memory with MongoDB Atlas

> Persist agent long-term memory with MongoDBStore and MongoDB Atlas.

[Long-term memory](/oss/python/langchain/long-term-memory) lets your agent store and recall information across different conversations and sessions. This guide shows how to use [MongoDB Atlas](https://www.mongodb.com/docs/atlas/) as the persistent store backend.

MongoDB stores memories as documents in a collection. With an Atlas Vector Search index, the same store can run semantic search over stored memories.

<Tip>
  For a deeper dive into memory types and strategies for writing memories, see the [Memory conceptual guide](/oss/python/concepts/memory#long-term-memory).
</Tip>

## Setup

### Installation

Install the store package (`langgraph-store-mongodb`):

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langgraph-store-mongodb pymongo
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langgraph-store-mongodb pymongo
  ```
</CodeGroup>

### Credentials

Set your Atlas connection string:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

if not os.environ.get("MONGODB_ATLAS_URI"):
    os.environ["MONGODB_ATLAS_URI"] = getpass.getpass("Enter your MongoDB Atlas URI: ")
```

If you want automated tracing of your model calls, set your [LangSmith](/langsmith/home) API key:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
if not os.environ.get("LANGSMITH_API_KEY"):
    os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## Usage

Create a `MongoDBStore` and pass it to `create_agent`. The `from_conn_string` context manager creates the required indexes when it opens. You do not call a separate `setup()` method.

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os

from langchain.agents import create_agent
from langgraph.store.mongodb import MongoDBStore

MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]

with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
    agent = create_agent(
        "anthropic:claude-sonnet-4-6",
        tools=[],
        store=store,
    )
```

## Memory storage

LangGraph stores memories as JSON documents organized by `namespace` and `key`. Namespaces typically include a user or org ID to keep memories scoped.

The following example configures vector indexing so `store.search` can run semantic queries. Use `create_vector_index_config` and pass it as `index_config`:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from collections.abc import Sequence

from langgraph.store.mongodb import MongoDBStore, create_vector_index_config

def embed(texts: Sequence[str]) -> list[list[float]]:
    # Replace with an embeddings model or LangChain Embeddings instance
    return [[1.0, 2.0] for _ in texts]

MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]

with MongoDBStore.from_conn_string(
    MONGODB_ATLAS_URI,
    index_config=create_vector_index_config(embed=embed, dims=2),
) as store:
    user_id = "my-user"
    application_context = "chitchat"
    namespace = (user_id, application_context)
    store.put(
        namespace,
        "a-memory",
        {
            "rules": [
                "User likes short, direct language",
                "User only speaks English and Python",
            ],
            "my-key": "my-value",
        },
    )
    item = store.get(namespace, "a-memory")
    items = store.search(
        namespace, filter={"my-key": "my-value"}, query="language preferences"
    )
```

For more information about store operations, see the [Stores](/oss/python/langgraph/stores) guide.

## Read long-term memory in tools

Tools can read from the store using the `runtime` parameter, which LangGraph injects automatically:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langgraph.store.mongodb import MongoDBStore

@dataclass
class Context:
    user_id: str

MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]

with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
    store.put(("users",), "user_123", {"name": "John Smith", "language": "English"})

    @tool
    def get_user_info(runtime: ToolRuntime[Context]) -> str:
        """Look up user info."""
        assert runtime.store is not None
        user_info = runtime.store.get(("users",), runtime.context.user_id)
        return str(user_info.value) if user_info else "Unknown user"

    agent = create_agent(
        "anthropic:claude-sonnet-4-6",
        tools=[get_user_info],
        store=store,
        context_schema=Context,
    )

    agent.invoke(
        {"messages": [{"role": "user", "content": "look up user information"}]},
        context=Context(user_id="user_123"),
    )
```

## Write long-term memory from tools

Tools can also write to the store using `runtime.store.put`, persisting data that survives across threads:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langgraph.store.mongodb import MongoDBStore
from typing_extensions import TypedDict

@dataclass
class Context:
    user_id: str

class UserInfo(TypedDict):
    name: str

@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    assert runtime.store is not None
    runtime.store.put(("users",), runtime.context.user_id, dict(user_info))
    return "Successfully saved user info."

MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]

with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
    agent = create_agent(
        "anthropic:claude-sonnet-4-6",
        tools=[save_user_info],
        store=store,
        context_schema=Context,
    )

    agent.invoke(
        {"messages": [{"role": "user", "content": "My name is John Smith"}]},
        context=Context(user_id="user_123"),
    )
```

## See also

* [Long-term memory](/oss/python/langchain/long-term-memory)
* [Store integrations](/oss/python/integrations/long-term-memory)
* [Short-term memory with MongoDB Atlas](/oss/python/integrations/memory/mongodb-short-term-memory)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>

  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/memory/mongodb-long-term-memory.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>
</div>
