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

**1. 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?")
```

**2. 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")
```

***

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

***

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

> [accordion] 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] 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] 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] 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.

> [!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`.

***

## Related

> [card] [Knowledge Backends](https://praison.ai/docs/features/knowledge-backends.md)
>
> Compare Chroma, mem0, and MongoDB storage backends

> [card] [MongoDB Memory](https://praison.ai/docs/features/mongodb-memory.md)
>
> Use MongoDB as the agent memory store

> [card] [Local Memory & Knowledge](https://praison.ai/docs/features/local-memory-and-knowledge.md)
>
> Run memory and knowledge fully local with Ollama embeddings

> [card] [Ollama Embeddings](https://praison.ai/docs/embeddings/providers/ollama.md)
>
> Local embedding models and their auto-detected dimensions


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