For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Integrate MongoDB with Strands Agents

You can integrate MongoDB with Strands Agents, an open-source Python SDK for building AI agents. The strands-mongodb package allows you to use a MongoDB deployment as the backend for the following classes:

  • MongoDBStorage, which persists agent sessions, context management, and transcripts in MongoDB.

  • MongoDBMemoryStore, which saves and recalls facts by semantic meaning, keyword, or a combination of both.

To complete a tutorial that configures Strands Agents to use MongoDB, see Get Started with the MongoDB Strands Agents Integration.

To install the strands-mongodb package and the dependencies for the MongoDBStorage and MongoDBMemoryStore classes, run the following command:

pip install 'strands-mongodb[all]'

This command installs the following dependencies:

  • strands-mongodb: The MongoDB integration package for Strands Agents.

  • strands-agents: The Strands Agents SDK. The package requires v1.54 or later.

  • pymongo: The official Python driver for MongoDB. The package requires v4.14 or later.

  • pymongo-search-utils: Utilities for working with MongoDB's vector search features. The package requires v0.3 or later.

  • opentelemetry-api: The OpenTelemetry API for Python. The package requires v1.30 or later.

  • typing-extensions: Backported typing features for Python. The package requires v4.13.2 or later.

Alternatively, install the dependencies for individual classes by running one of the following commands:

pip install 'strands-mongodb[storage]' # MongoDBStoragepip install 'strands-mongodb[memory]' # MongoDBMemoryStore

To configure your MongoDB connection, pass a MongoDBConfig dictionary to the MongoDBStorage or MongoDBMemoryStore class. Create one MongoDBConfig dictionary per process and pass it to every class you use, which allows them to share one connection pool.

You can specify either an existing client or a connection string to configure your connection. Select the Existing client or Connection string tab to view a corresponding example:

from pymongo import AsyncMongoClientfrom strands_mongodb.types import MongoDBConfig client = AsyncMongoClient("<connection-string>")connection: MongoDBConfig = { "client": client, "database": "agents",}

Note

The package doesn't take ownership of the client. You are responsible for closing it.

To learn more about AsyncMongoClient, see Create a MongoClient.

The MongoDBStorage class allows you to save an agent's persistent data in MongoDB. Once configured, the SDK stores the agent's sessions, context management data, and transcripts as documents in a MongoDB collection instead of in local files or memory. The persistent data is stored under string keys, and each key becomes a document's _id value. As a result, read and write operations perform primary-key lookups.

This section describes how to configure and use the methods provided by the MongoDBStorage class.

To configure this class, pass a MongoDBConfig dictionary and a collection name to the MongoDBStorage constructor. The following example writes persistent data to MongoDB, retrieves this data, lists keys that start with a specified prefix, and deletes the data:

import asyncio from strands_mongodb import MongoDBStorage async def main() -> None: storage = MongoDBStorage(connection, collection="storage") try: await storage.write("notes/colony", b"emperor penguins live in Antarctica") print(await storage.read("notes/colony")) print(await storage.list("notes/")) await storage.delete("notes/colony") finally: await storage.close() asyncio.run(main())

To learn how to configure an agent to use this class, see Configure an Agent.

The following table lists the methods provided by the MongoDBStorage class:

Method
Description
Parameters
Return Value

write()

Stores persistent data as bytes in a key, replacing any existing value. If you set ttl_seconds, this method also adds an expires_at field to the document it writes.

key: The key to store the data under.
data: The bytes to store.

None

read()

Returns the bytes stored in a key.

key: The key to read.

bytes, or None when the key is absent

delete()

Removes one key. If you delete a key that doesn't exist, this method doesn't raise an error.

key: The key to remove.

None

list()

Returns the names of keys that start with a prefix, in ascending order. Returns keys only, not the stored values.

query: The key prefix to match.

list[str]

search()

By default, this method ranks stored key names by how many words they share with a query. To search the stored values instead, set MongoDBStorage's search_strategy parameter to a strategy that reads values, such as the SDK's KeywordSearchStrategy or MongoDBVectorSearchStrategy for vector search.

query: The text to search for.

list[StorageSearchResult]

delete_prefix()

Removes every key that starts with a specified prefix.

prefix: The key prefix to remove.

int, which indicates the number of documents removed

namespace()

Returns a new MongoDBStorage scoped to a prefix in the same collection, sharing the original connection pool, collection, TTL, and search strategy. This method is synchronous.

prefix: The prefix that scopes the new instance.

MongoDBStorage

ensure_indexes()

Creates or verifies the TTL index that ttl_seconds requires. Call this method once at startup.

None

None

close()

Releases the connection pool for every instance that shares the same MongoDBConfig dictionary. Call this method once at process shutdown.

None

None

When you pass a MongoDBStorage instance to an Agent, the agent's session and context subsystems call write(), read(), delete(), list(), and search() for you. You call ensure_indexes(), close(), namespace(), and delete_prefix() yourself.

The MongoDBMemoryStore class allows you to save an agent's long-term memory in MongoDB. Once configured, the agent stores facts in a MongoDB collection and retrieves them by meaning, by keyword, or both. The store uses MongoDB Vector Search for semantic recall and MongoDB Search for keyword recall.

To use MongoDB Vector Search, MongoDB compares the vector embeddings of your data with the embedding of the query. By default, MongoDB generates these embeddings for you, so you don't need to manage vectors or embedding provider API keys.

This section describes how to configure and use the methods provided by the MongoDBMemoryStore class.

To configure this class, pass a name and a MongoDBConfig dictionary to the MongoDBMemoryStore constructor.

This example creates a memory store, adds a memory, and then searches for the memory by semantic meaning. When instantiating a MongoDBMemoryStore, the example also sets the following optional parameters:

  • scope: Limits the memory store's access to documents that store the specified scope field value. The example uses the scope "user-abc".

  • writable: Enables write operations on the memory store.

import asyncio from strands_mongodb import MongoDBMemoryStore async def main() -> None: store = MongoDBMemoryStore( name="preferences", config=connection, scope="user-abc", writable=True ) try: await store.add("Studies emperor penguins in Antarctica.") results = await store.search("Which animals does this researcher observe?") for entry in results: print(f"search type: {entry.metadata['_search_type']}") print(f"score: {entry.metadata['_relevance_score']}") print(f"content: {entry.content}") finally: await store.close() asyncio.run(main())

MongoDBMemoryStore uses the following search types to answer a query:

  • Vector search, which matches by meaning.

  • Text search, which matches by keyword.

  • Hybrid search, which combines both search types.

The search_type key in the MongoDBConfig dictionary controls which search types the store uses. The default value, "auto", prepares every search type the deployment supports and prefers the highest one available.

Because this deployment prepares both indexes, a search_type value of "auto" uses hybrid search. Hybrid search ranks results differently from vector search, so scores from the two are not directly comparable. A min_score or max_score value that you configured for vector search can exclude results that you expect to keep.

To learn how to configure an agent to use this class, see Configure an Agent.

The following table lists the methods provided by the MongoDBMemoryStore class:

Method
Description
Parameters
Return Value

add()

Stores one memory in this store's scope. Writes are deduplicated on scope, store name, and content, so adding the same fact again doesn't create a second document.

content: The text of the memory.
metadata: Optional key-value pairs to store with the memory.

MongoDBAddResult, which contains ids, inserted, and duplicates

search()

Returns the memories that best match a query in order of relevance. Accepts a plain string or a MongoDBSearchQuery dictionary for a per-query filter, limit, or vector.

query: The text to search for, or a MongoDBSearchQuery dictionary.
options: Optional SDK search options, such as max_search_results.

list[MemoryEntry]. Each entry's metadata includes _relevance_score, _search_type, _scope, and _id.

initialize()

Identifies which search features the deployment supports, and then creates this store's indexes. This method is called automatically by MemoryManager and by every method that reads or writes memories.

None

None

delete()

Deletes one memory, identified by the _id that a search result reports. To use this method, you must set writable to True.

memory_id: The _id value from a search result.

int, which is 1 if a document was deleted or 0 if none matched

delete_all()

Deletes every memory that this store can read. To use this method, you must set writable to True.

None

int, which indicates the number of documents deleted

close()

Releases the connection pool for every instance that shares the same MongoDBConfig dictionary.

None

None

When you register this store with MemoryManager, the agent calls initialize(), search(), and, when you enable it, add(). You call delete(), delete_all(), and close() yourself, because the SDK's MemoryStore interface has no deletion or connection methods.

You can configure an agent to store its sessions and long-term memory in the same MongoDB deployment. This configuration lets the agent save and retrieve that data automatically as it runs.

To configure the agent, pass a MongoDBConfig dictionary to both the MongoDBStorage and MongoDBMemoryStore constructors, then pass the resulting instances to the Agent constructor.

The following example creates an agent that uses MongoDB for both sessions and memory:

from strands import Agentfrom strands.memory import MemoryManagerfrom strands.session import SnapshotSessionManagerfrom strands_mongodb import MongoDBStorage, MongoDBMemoryStore store = MongoDBMemoryStore( name="preferences", config=connection, scope="user-abc", writable=True,) agent = Agent( model=your_model, storage=MongoDBStorage(connection), session_manager=SnapshotSessionManager(session_id="support-ticket-4127"), memory_manager=MemoryManager(stores=[store], add_tool_config=True),)

The following considerations apply:

  • To allow the agent to save memories, set the writable key to True.

  • The MemoryManager class always provides the model with a search_memory tool, but it provides an add_memory tool only when add_tool_config is set to True. If you want the model to decide when to save a memory, enable the add_tool_config parameter.

  • The add_tool_config parameter raises a ValueError if no store you pass is writable.

  • The storage parameter alone does not persist sessions. You must set session_manager to save the sessions under the specified session_id value.

MongoDBMemoryStore creates two search indexes on first use, unless you set the ensure_indexes key to False.

The MongoDB Vector Search index is named by the MongoDBConfig dictionary's vector_index_name key and has the following definition:

{ "fields": [ { "type": "autoEmbed", "path": "content", "model": "voyage-4-lite", "modality": "text" }, { "type": "filter", "path": "scope" }, { "type": "filter", "path": "store_name" } ]}

Note

By default, this MongoDB Vector Search index uses the autoEmbed type, which instructs MongoDB to generate the embeddings automatically.

The MongoDB Search index is named by the MongoDBConfig dictionary's text_index_name key and has the following definition:

{ "mappings": { "dynamic": false, "fields": { "content": [{ "type": "string" }] } }}

To learn more about creating these indexes manually, see Create a MongoDB Vector Search Index and MongoDB Search Index.

To supply your own vector embeddings, set the MongoDBConfig dictionary's embedding_dimensions and similarity keys. Do not set the embedding_model key. With this configuration, MongoDB indexes an embedding field as the vector type, instead of a content field as the autoEmbed type.

Then, provide the vectors in one of the following ways:

  • Pass an embedder object to the MongoDBMemoryStore constructor, which instructs the store to embed memories and string queries

  • When calling the search() method, pass a precomputed vector in the vector key of a MongoDBSearchQuery dictionary

The following table describes the privileges that your database user requires for different actions:

Privilege
Needed For
Required When

Every read, on both classes

Always

write(), add(), delete(), and similar methods

Always, for a writable store or storage instance

Collation check that every initialize() call runs before any index

Always

Verifying indexes

Always

Creating indexes

Only when ensure_indexes is set to True, its default value

To grant these privileges, create a custom role scoped to your storage and memory collections.

Note

By default, the initialize() and ensure_indexes() methods create the indexes the package requires if they don't already exist. Production applications often run as a user without the createIndex, createCollection, and createSearchIndexes privileges, or leave index creation to a separate deployment step. In that case, set the MongoDBConfig dictionary's ensure_indexes key to False. This instructs the package to verify the indexes instead of creating them.

To learn more about using Strands Agents with MongoDB, see the following resources: