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

# MongoDB Memory

> Configure MongoDB and Atlas Vector Search for agent memory

Use MongoDB as a document-backed memory store with optional Atlas Vector Search for semantic retrieval.

<Note>
  This is PraisonAI's first-party MongoDB memory adapter. It is **not** the same as running mem0 with a MongoDB vector store backend. Mem0's MongoDB vector store has an [upstream bug](https://github.com/mem0ai/mem0/issues/3185); the adapter documented on this page is a separate implementation and is unaffected. See [Memory Troubleshooting](/docs/docs/features/memory-troubleshooting#why-is-memory-mem0-returning-empty-search-results-mongodb-vector-store) if you were sent here from a mem0 error.
</Note>

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="assistant",
    instructions="Remember facts across sessions.",
    memory={
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb://localhost:27017/",
            "database": "praisonai",
            "use_vector_search": True,
            "embedder": {
                "provider": "ollama",
                "config": {"model": "nomic-embed-text"},
            },
        },
    },
)
agent.start("Remember that my favourite colour is teal")
```

The user chats with the agent; short- and long-term memory persist in MongoDB, embedded fully local through Ollama.

Prefer the shortest, flat form? Use `embedding_model` directly:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="assistant",
    memory={
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb://localhost:27017/",
            "database": "praisonai",
            "use_vector_search": True,
            "embedding_model": "ollama/nomic-embed-text",
        },
    },
)
```

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "MongoDB Memory"
        A[Agent] --> B[Memory]
        B --> C[(Short-term)]
        B --> D[(Long-term)]
        C --> E[Vector Search]
        D --> E
    end

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef store fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class A agent
    class B process
    class C,D store
    class E output
```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as MongoDB Memory

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result    Agent-->>User: Response
```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="assistant",
        memory={
            "provider": "mongodb",
            "config": {
                "connection_string": "mongodb://localhost:27017/",
                "database": "praisonai",
            },
        },
    )
    ```
  </Step>

  <Step title="With Configuration">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import os
    from praisonaiagents import Agent

    agent = Agent(
        name="assistant",
        memory={
            "provider": "mongodb",
            "config": {
                "connection_string": os.getenv("MONGODB_URI", "mongodb://localhost:27017/"),
                "database": "praisonai",
                "use_vector_search": True,
            },
        },
    )
    ```
  </Step>
</Steps>

<Note>
  Install the optional dependency first: `pip install pymongo` or `pip install "praisonaiagents[mongodb]"`.
</Note>

## Configuration

| Option                     | Type   | Default                      | Description                                                                                                                                    |
| -------------------------- | ------ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `connection_string`        | `str`  | `mongodb://localhost:27017/` | MongoDB URI                                                                                                                                    |
| `database`                 | `str`  | `praisonai`                  | Database name                                                                                                                                  |
| `use_vector_search`        | `bool` | `False`                      | Enable Atlas Vector Search on short-term and long-term memory                                                                                  |
| `embedding_model`          | `str`  | `"text-embedding-3-small"`   | Embedding model as a litellm string (e.g. `"ollama/nomic-embed-text"`). Wins over `embedder`.                                                  |
| `embedder`                 | `dict` | `None`                       | Alternative shape: `{"provider": "...", "config": {"model": "..."}}`. Recombined into `"<provider>/<model>"` for litellm; `openai` stays bare. |
| `max_pool_size`            | `int`  | `50`                         | Connection pool maximum                                                                                                                        |
| `min_pool_size`            | `int`  | `10`                         | Connection pool minimum                                                                                                                        |
| `max_idle_time`            | `int`  | `30000`                      | Max idle time in ms                                                                                                                            |
| `server_selection_timeout` | `int`  | `5000`                       | Server selection timeout in ms                                                                                                                 |

<Note>
  As of PraisonAI [#4203](https://github.com/MervinPraison/PraisonAI/pull/4203), MongoDB memory scopes `collection_name` per agent by default (`memory_store_<user_id>`) so two agents in one process don't share one collection. Set `collection_name` explicitly to keep a shared collection. See [Per-agent isolation across backends](/docs/features/multi-agent-memory#per-agent-isolation-across-backends).
</Note>

## Vector Search

When `use_vector_search: True`:

* **Both** short-term and long-term writes include an embedding — using `text-embedding-3-small` by default, or whatever you configure (see below).
* Searches use MongoDB `$vectorSearch` against index `vector_index` on field `embedding` — the same field in both collections.
* If vector search fails or is unavailable, either tier falls back to MongoDB text search.

When `use_vector_search: False` (default), only MongoDB text indexes are used.

### Configuring the embedding model

The adapter resolves the embedding model at construction, in this precedence order: `embedding_model` → `config["embedder"]` → falls back to `text-embedding-3-small`.

Use the `embedder` block (preferred — the same shape used across memory, knowledge, and the MongoDB knowledge adapter):

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="assistant",
    memory={
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb://localhost:27017/",
            "database": "praisonai",
            "use_vector_search": True,
            "embedder": {
                "provider": "ollama",
                "config": {"model": "mxbai-embed-large"},
            },
        },
    },
)
```

Or the flat `embedding_model` string (litellm-style, shortest):

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="assistant",
    memory={
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb://localhost:27017/",
            "database": "praisonai",
            "use_vector_search": True,
            "embedding_model": "ollama/nomic-embed-text",
        },
    },
)
```

<Note>
  Atlas vector search indexes are **built for a specific dimension**. Switching from `text-embedding-3-small` (1536) to `nomic-embed-text` (768) means you must re-create the `vector_index` on **both** `short_term_memory` and `long_term_memory` at the new dimension. Otherwise writes succeed but searches error or return nothing.
</Note>

<Info>
  **Configurable embedder ([PR #4802](https://github.com/MervinPraison/PraisonAI/pull/4802)):** Before this fix the adapter hardcoded `text-embedding-3-small`. An agent configured entirely against Ollama still silently embedded through OpenAI — and if that OpenAI call failed, documents were written with no vectors and vector search degraded to text search with no warning. The adapter now honours `embedding_model` / `embedder`, mirroring the MongoDB knowledge adapter.
</Info>

<Info>
  **Short-term embeddings parity ([PR #3419](https://github.com/MervinPraison/PraisonAI/pull/3419)):** Before #3419, `use_vector_search: True` produced embeddings only for long-term writes and searches. Short-term writes were text-only, so semantic recall on recent context silently degraded to keyword lookup. The adapter now uses the shared `_store` / `_search` helpers for all four operations, matching `DakeraMemoryAdapter`.
</Info>

<Info>
  As of PraisonAI PR #2060, `use_vector_search` is always initialised on the `Memory` instance — even when MongoDB is not the active provider. Previously, a missing attribute could raise `AttributeError` deep in store/search paths.
</Info>

## Atlas Setup

1. Create a vector search index named `vector_index` on **both** the `short_term_memory` and `long_term_memory` collections.
2. Set the indexed path to `embedding` on each.
3. Pass `use_vector_search: True` in agent config.

## Best Practices

<AccordionGroup>
  <Accordion title="Use environment variables for credentials">
    Store connection strings in `MONGODB_URI` rather than hard-coding credentials in source files.
  </Accordion>

  <Accordion title="Enable vector search for semantic recall">
    Set `use_vector_search: True` on Atlas when you need similarity search; text indexes suffice for keyword lookup.
  </Accordion>

  <Accordion title="Size the connection pool for concurrency">
    Tune `max_pool_size` and `min_pool_size` when running many agents against the same cluster.
  </Accordion>

  <Accordion title="Create indexes before production traffic">
    Configure the `vector_index` Atlas index and text indexes before scaling agent workloads.
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card title="Custom Memory Adapters" icon="brain" href="/docs/features/custom-memory-adapters">
    Registry pattern and custom backend registration.
  </Card>

  <Card title="Memory Advanced Search" icon="magnifying-glass-plus" href="/docs/features/memory-advanced-search">
    Reranking, relevance cutoffs, and quality filtering.
  </Card>

  <Card title="Dakera Memory" icon="database" href="/docs/features/dakera-memory">
    Self-hosted, decay-weighted vector recall via the Dakera server.
  </Card>

  <Card title="Local Memory & Knowledge" icon="server" href="/docs/features/local-memory-and-knowledge">
    Run memory and knowledge fully local with Ollama embeddings.
  </Card>

  <Card title="Ollama Embeddings" icon="server" href="/docs/embeddings/providers/ollama">
    Local embedding models and their auto-detected dimensions.
  </Card>
</CardGroup>
