You can integrate MongoDB with Agno, an open-source Python framework for building multi-modal AI agents. Agno provides two MongoDB integrations:
Vector database that stores your agent's knowledge base and retrieves it with MongoDB Vector Search.
Session and memory database that persists agent sessions, user memories, metrics, and evaluation runs in your MongoDB collections.
You can use either integration on its own, or you can use both in the same agent.
Get Started
To complete a tutorial that configures Agno to use MongoDB, see Get Started with the MongoDB Agno Integration.
Installation
Agno requires Python v3.9 or later. To install the latest Agno and PyMongo versions, run the following command:
pip install agno pymongo
The examples on this page use OpenAI models, which Agno uses by default. To install the OpenAI client library, run the following command:
pip install openai
The Custom configuration examples on this page use Voyage AI embeddings. To install the Voyage AI client library, run the following command:
pip install voyageai
Environment Variables
Before running the examples on this page, set the following environment variables:
Connection string: Set
MONGODB_URIto the connection string for your MongoDB deployment.Model API key: Set
OPENAI_API_KEYorVOYAGE_API_KEYto the API key for your model provider.
Vector Database
The MongoVectorDb class implements the Agno vector database interface with MongoDB Vector Search. To give an agent semantic search over your documents, pass an instance of this class to the vector_db parameter of an Agno Knowledge object, then pass that object to the knowledge parameter of your agent.
Important
MongoDB Class Names
Agno names both MongoDB classes MongoDb, but imports them from different modules. Import the vector database class from agno.vectordb.mongodb and the database class from agno.db.mongo. To avoid a name collision, Agno also exports the vector database class as MongoVectorDb. The examples on this page use that alias.
Select the Basic initialization tab to view a minimal configuration example, or select the Custom configuration tab to see how to configure the integration with custom settings.
To initialize the vector database, specify the collection that stores your embeddings and your MongoDB connection string. The following example creates a knowledge base, adds a document, and gives an agent access to the data:
import os from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.vectordb.mongodb import MongoVectorDb vector_db = MongoVectorDb( collection_name="agent_knowledge", db_url=os.environ["MONGODB_URI"], database="agno", ) knowledge = Knowledge(vector_db=vector_db) knowledge.insert( name="Recipes", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", ) agent = Agent(knowledge=knowledge, search_knowledge=True)
The following example enables hybrid search, uses Voyage AI to generate embeddings instead of the OpenAI default, and specifies a MongoDB Vector Search index name:
import os from agno.agent import Agent from agno.knowledge.embedder.voyageai import VoyageAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.vectordb.mongodb import MongoVectorDb from agno.vectordb.search import SearchType embedder = VoyageAIEmbedder( id="voyage-4-large", dimensions=1024, api_key=os.environ["VOYAGE_API_KEY"], request_params={"output_dimension": 1024}, ) vector_db = MongoVectorDb( collection_name="agent_knowledge", db_url=os.environ["MONGODB_URI"], database="agno", embedder=embedder, search_type=SearchType.hybrid, hybrid_vector_weight=0.7, hybrid_keyword_weight=0.3, search_index_name="agno_vector_index", ) knowledge = Knowledge(vector_db=vector_db) agent = Agent(knowledge=knowledge, search_knowledge=True)
If you specify an embedder, Agno uses the number of dimensions that the embedder produces when it creates the MongoDB Vector Search index. The request_params dictionary passes provider-specific keyword arguments to the embedding call. For Voyage AI, output_dimension controls the size of the returned vector for models that support variable dimensions.
When you create a Knowledge object, Agno verifies whether the collection already exists. If it doesn't, Agno creates the collection and the MongoDB Vector Search index. If the collection exists, Agno doesn't check whether the index exists, even if you deleted it separately.
After creating the index, Agno waits until the index appears on the collection. However, it doesn't verify the index status, so a query that runs immediately afterward can return no results while the index finishes building.
The MongoVectorDb class accepts the following parameters:
Parameter | Necessity | Description |
|---|---|---|
| Required | The name of the collection that stores your documents and their embeddings. |
| Optional | The connection string for your MongoDB deployment. Defaults to |
| Optional | An existing |
| Optional | The name of the database that holds the collection. Defaults to |
| Optional | The embedding model that Agno uses to embed your documents and queries. Defaults to |
| Optional | The similarity function that the MongoDB Vector Search index uses. Only the default value, |
| Optional | The retrieval strategy. Accepts |
| Optional | The weight that hybrid search applies to semantic results. Defaults to |
| Optional | The weight that hybrid search applies to keyword results. Defaults to |
| Optional | The constant that hybrid search adds to each rank before it computes the reciprocal rank fusion score. Defaults to |
| Optional | The name of the MongoDB Vector Search index on your collection. Defaults to |
| Optional | Whether Agno waits, after creating the MongoDB Vector Search index, for the index name to appear in the collection's search indexes. Set this parameter to a positive number to wait, or to |
| Optional | The time, in seconds, that Agno waits after it inserts documents. Defaults to |
| Optional | The maximum number of connections in the driver connection pool. Defaults to |
| Optional | Whether the driver retries supported write operations. Defaults to |
| Optional | Whether Agno creates indexes in the Azure Cosmos DB for MongoDB vCore format instead of the MongoDB Vector Search format. Defaults to |
| Optional | The identifying metadata for the vector database instance. If you don't specify |
Vector Database Methods
The Knowledge class calls the following methods when you add content to a knowledge base or when an agent searches it. Call these methods directly only if you manage documents outside of a Knowledge object.
To limit a write or search operation to one user's documents, pass a user_id value to the operation method.
Method | Description |
|---|---|
| Embeds |
| Embeds each document in |
| Replaces the documents that share |
| Deletes every document from your collection but keeps the collection and its MongoDB Vector Search index. |
| Deletes the document with the specified |
| Deletes the documents with the specified |
| Deletes the documents whose |
| Drops your collection and its MongoDB Vector Search index. |
| Returns |
| Returns the number of documents in your collection. |
Tip
Asynchronous Methods
The following methods described in the preceding table each have a corresponding asynchronous method:
search(): Useasync_search()insert(): Useasync_insert()upsert(): Useasync_upsert()drop(): Useasync_drop()exists(): Useasync_exists()
Session and Memory Database
The MongoDb class in the agno.db.mongo module implements the Agno database interface. To persist an agent's sessions, user memories, metrics, and evaluation runs in MongoDB, pass an instance of this class to the db parameter of an Agent, Team, or Workflow object.
Select the Basic initialization tab to view a minimal configuration example, or select the Custom configuration tab to see how to configure the integration with custom settings.
To initialize the database, specify your MongoDB connection string. The following example creates an agent that stores its session history in MongoDB and includes that history in the model context:
import os from agno.agent import Agent from agno.db.mongo import MongoDb db = MongoDb(db_url=os.environ["MONGODB_URI"]) agent = Agent(db=db, add_history_to_context=True)
The following example specifies the database name and the names of the collections that store sessions, memories, and metrics:
import os from agno.agent import Agent from agno.db.mongo import MongoDb db = MongoDb( db_url=os.environ["MONGODB_URI"], db_name="agno_prod", session_collection="agent_sessions", memory_collection="agent_memories", metrics_collection="agent_metrics", ) agent = Agent(db=db, add_history_to_context=True)
Agno creates each collection that you configure the first time it writes to that collection.
The MongoDb class accepts the following parameters:
Parameter | Necessity | Description |
|---|---|---|
| Conditional | The connection string for your MongoDB deployment. Required if you don't specify |
| Conditional | An existing |
| Optional | The name of the database that holds the collections. Defaults to |
| Optional | The name of the collection that stores agent, team, and workflow sessions. Defaults to |
| Optional | The name of the collection that stores runs, with one document per run. Defaults to |
| Optional | The name of the collection that stores user memories. Defaults to |
| Optional | The name of the collection that stores aggregated usage metrics. Defaults to |
| Optional | The name of the collection that stores evaluation runs. Defaults to |
| Optional | The name of the collection that stores knowledge content metadata. Defaults to |
| Optional | The names of the collections that store traces and spans. Default to |
| Optional | The names of the collections that store schedules and schedule runs. Default to |
| Optional | The name of the collection that stores learnings. Defaults to |
| Optional | The identifier for the database instance. If you don't specify this parameter, Agno derives it from the connection string and database name. |
As your agent runs, Agno automatically reads from and writes to the session, memory, and metrics collections described in this section. Agno creates each collection the first time it's needed. You can also call methods directly on your MongoDb instance, such as the following:
upsert_session()andget_sessions()read and write sessions.upsert_user_memory()writes a single user memory.get_metrics()reads aggregated usage metrics.upsert_sessions()andupsert_memories()write many records in a single operation, such as when you migrate existing session history into MongoDB.close()releases the client connection. Call this method when your application shuts down.
Search Index
The first time Agno creates your vector collection, it also creates an MongoDB Vector Search index on the collection. The index name is the value of the search_index_name parameter, which defaults to vector_index_1. You can also create or inspect this index manually. To learn more, see Create a MongoDB Vector Search Index.
The index uses the following definition, where numDimensions matches the number of dimensions that your embedder produces and similarity matches your distance_metric value:
{ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 1536, "similarity": "cosine" }, { "type": "filter", "path": "user_id" } ] }
Agno indexes the user_id field as a filter field so that it can scope searches to a single end user's documents.
Hybrid search doesn't require a MongoDB Search index. Agno runs its keyword search as a regular expression query on the content field, then combines those results with the MongoDB Vector Search results by using reciprocal rank fusion.
Additional Resources
To learn more about using Agno with MongoDB, see the following resources:
Agno MongoDB Vector Store reference
Agno MongoDB Database reference
Agno Knowledge documentation
Agno GitHub repository