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

> Use MongoDB Atlas as a scoped, vector-searchable knowledge backend

Store agent knowledge in MongoDB Atlas with per-tenant `user_id` / `agent_id` / `run_id` scope on every read and write.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "MongoDB Knowledge"
        A[🤖 Agent] --> B[📥 add / 🔎 search]
        B --> C[🍃 MongoDB Atlas]
        C --> D[✅ Scoped results]
    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 store
    class D output
```

## Quick Start

<Steps>
  <Step title="Agent with MongoDB knowledge">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig

    agent = Agent(
        name="SupportBot",
        instructions="Answer using the customer's session history.",
        knowledge={
            "vector_store": {
                "provider": "mongodb",
                "config": {
                    "connection_string": "mongodb+srv://...",
                    "database": "praison",
                    "collection": "support_knowledge",
                },
            },
        },
        memory=MemoryConfig(user_id="customer_42", session_id="session_2026_08_09"),
    )

    agent.start("What did we agree on for the refund?")
    ```
  </Step>

  <Step title="Direct Knowledge API">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Knowledge

    kb = Knowledge(config={
        "vector_store": {
            "provider": "mongodb",
            "config": {
                "connection_string": "mongodb+srv://...",
                "database": "praison",
                "collection": "support_knowledge",
            },
        }
    })

    kb.add("Refund promised: $49 by Aug 12.",
           user_id="customer_42", agent_id="support_bot_v1", run_id="session_2026_08_09")

    kb.search("refund promise",
              user_id="customer_42", agent_id="support_bot_v1", run_id="session_2026_08_09")
    ```
  </Step>
</Steps>

***

## How It Works

The adapter persists `user_id` / `agent_id` / `run_id` on each document and applies any provided scope as a pre-filter on search.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    Q[🔎 Query + scope] --> V{Atlas vector<br/>search available?}
    V -->|Yes| VS["$vectorSearch<br/>filter: user_id / agent_id / run_id"]
    V -->|No| TS["find #40;$text#41; + scope filter"]
    VS --> R[✅ Scoped results]
    TS --> R

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class Q input
    class V decision
    class VS,TS process
    class R output
```

On Atlas `$vectorSearch`, the scope becomes the stage-level `filter`. Without Atlas vector search, the adapter falls back to MongoDB text search and merges the scope into the `find()` query. `None` values are dropped — omit an identifier to broaden the search on that dimension.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant Adapter as MongoDB adapter
    participant Atlas as MongoDB Atlas

    Agent->>Adapter: search(query, user_id=..., agent_id=...)
    Adapter->>Atlas: $vectorSearch(filter=scope)
    Atlas-->>Adapter: nearest documents in scope
    Adapter-->>Agent: scoped results
```

***

## Full Method Surface

Since PR [#5320](https://github.com/MervinPraison/PraisonAI/pull/5320) the MongoDB adapter implements the full `KnowledgeStoreProtocol`. Methods taking scope require at least one of `user_id` / `agent_id` / `run_id`; `get` / `update` / `delete` operate on a specific `item_id` and need no scope.

| Method | Signature (key args) | Returns | Raises |
| - | - | - | - |
| `add(text, metadata?, user_id?, agent_id?, run_id?)` | ≥1 scope required | `str` (document ID) | `ScopeRequiredError` |
| `search(query, limit=5, user_id?, agent_id?, run_id?, filters?)` | ≥1 scope required | `List[dict]` | `ScopeRequiredError` |
| `get_all(user_id?, agent_id?, run_id?, limit=100)` | ≥1 scope required | `SearchResult` | `ScopeRequiredError` |
| `delete_all(user_id?, agent_id?, run_id?)` | ≥1 scope required | `bool` | `ScopeRequiredError` |
| `get(item_id)` | — | `SearchResultItem \| None` | — |
| `update(item_id, content, metadata?)` | — | `AddResult` | — |
| `delete(document_id)` | — | `bool` | — |

***

## Configuration Options

Config keys read from `MongoDBKnowledgeAdapter.__init__` under `vector_store.config`.

| Option | Type | Default | Description |
| - | - | - | - |
| `connection_string` | `str` | `"mongodb://localhost:27017/"` | MongoDB connection URI (use `mongodb+srv://...` for Atlas) |
| `database` | `str` | `"praisonai"` | Database name |
| `collection` | `str` | `"knowledge_base"` | Collection name |
| `use_vector_search` | `bool` | `True` | Enable Atlas `$vectorSearch`; falls back to text search when unavailable |

Embeddings are configured via the top-level `embedder` key. The adapter recombines it into a litellm string as `"<provider>/<model>"` — except `openai`, which stays bare. It falls back to `text-embedding-3-small` when nothing is set:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
config = {
    "vector_store": {
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb+srv://...",
            "database": "praison",
            "collection": "support_knowledge",
        },
    },
    "embedder": {
        "provider": "openai",
        "config": {"model": "text-embedding-3-small"},
    },
}
```

Run knowledge fully local by pointing the same `embedder` block at Ollama:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
config = {
    "vector_store": {
        "provider": "mongodb",
        "config": {
            "connection_string": "mongodb://localhost:27017/",
            "database": "praison",
            "collection": "support_knowledge",
        },
    },
    "embedder": {
        "provider": "ollama",
        "config": {"model": "nomic-embed-text"},
    },
}
```

<Note>
  Atlas vector search indexes are **built for a specific dimension**. Switching the embedder model — e.g. from `text-embedding-3-small` (1536) to `nomic-embed-text` (768) — means you must re-create the vector index on the collection at the new dimension, or searches will error or return nothing.
</Note>

***

## Common Patterns

Isolate a single customer's session by combining all three scopes:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
kb.search("refund promise",
          user_id="customer_42", agent_id="support_bot_v1", run_id="session_2026_08_09")
```

Broaden across all sessions for one customer by omitting `run_id`:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
kb.search("refund history", user_id="customer_42")
```

Narrow the search to a single metadata field with `filters=`:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Narrow the search to a single metadata field
kb.search("policy questions",
          user_id="customer_42",
          filters={"category": "policy"})
```

The MongoDB adapter silently dropped `filters` before PR [#5320](https://github.com/MervinPraison/PraisonAI/pull/5320); it now folds each key in as `metadata.<key>` alongside the scope on both Atlas `$vectorSearch` and the text-search fallback.

***

## Best Practices

<AccordionGroup>
  <Accordion title="Use Atlas for vector search">
    `use_vector_search=True` needs a MongoDB Atlas cluster with a vector index on the `embedding` path (similarity `cosine`). Without Atlas, the adapter transparently falls back to text search.
  </Accordion>

  <Accordion title="Always pass scope for multi-tenant apps">
    Provide `user_id` (and optionally `agent_id` / `run_id`) on both `add()` and `search()` to keep tenants isolated. Omitted scopes broaden the search on that dimension.
  </Accordion>

  <Accordion title="Prefer the Agent API">
    Passing `knowledge={...}` and `user_id=...` on the `Agent` handles scoping and context injection automatically. Use the direct `Knowledge` class only for custom indexing or search control.
  </Accordion>

  <Accordion title="Use mongodb+srv:// for Atlas connections">
    Atlas connection strings start with `mongodb+srv://` or contain `mongodb.net` — the adapter detects these to enable vector search.
  </Accordion>
</AccordionGroup>

<Note>
  Since PR [#3810](https://github.com/MervinPraison/PraisonAI/pull/3810), the MongoDB adapter honors `user_id` / `agent_id` / `run_id` on `add()` and `search()`. Since PR [#5320](https://github.com/MervinPraison/PraisonAI/pull/5320), it also **enforces** those scopes: an unscoped `add()` / `search()` / `get_all()` / `delete_all()` raises `ScopeRequiredError` (previously an unscoped `search()` silently returned every tenant's documents). The adapter also now defines `get_all()`, `delete_all()`, `update()`, and `get()` — earlier releases raised `AttributeError` for those calls on a MongoDB-backed `Knowledge`.
</Note>

***

## Related

<CardGroup cols={2}>
  <Card title="Knowledge Backends" icon="database" href="/docs/features/knowledge-backends">
    Compare Chroma, mem0, and MongoDB storage backends
  </Card>

  <Card title="MongoDB Memory" icon="brain" href="/docs/features/mongodb-memory">
    Use MongoDB as the agent memory store
  </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>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.