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.
Docs Menu

Integrate MongoDB with the Agno Framework

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.

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

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

Before running the examples on this page, set the following environment variables:

  • Connection string: Set MONGODB_URI to the connection string for your MongoDB deployment.

  • Model API key: Set OPENAI_API_KEY or VOYAGE_API_KEY to the API key for your model provider.

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)

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

search(query, limit, filters, min_score, user_id)

Embeds query and returns up to limit matching documents. If you set search_type to SearchType.hybrid, Agno also runs a keyword search and merges the two result sets. The filters parameter accepts a dictionary of metadata filters. If you pass a list of Agno filter expressions instead, Agno logs a warning and applies no filters because the MongoDB integration doesn't support them.

insert(content_hash, documents, filters, user_id)

Embeds each document in documents and inserts the documents into your collection. Agno derives each document's _id value from a hash of the document content.

upsert(content_hash, documents, filters, user_id)

Replaces the documents that share content_hash, then inserts the documents in documents. Use this method to update a document whose content changed.

delete()

Deletes every document from your collection but keeps the collection and its MongoDB Vector Search index.

delete_by_id(id)

Deletes the document with the specified _id value.

delete_by_name(name)

Deletes the documents with the specified name value.

delete_by_metadata(metadata)

Deletes the documents whose meta_data field matches the specified key-value pairs.

drop()

Drops your collection and its MongoDB Vector Search index.

exists()

Returns True if your collection exists.

get_count()

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(): Use async_search()

  • insert(): Use async_insert()

  • upsert(): Use async_upsert()

  • drop(): Use async_drop()

  • exists(): Use async_exists()

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)

Agno creates each collection that you configure the first time it writes to that collection.

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() and get_sessions() read and write sessions.

  • upsert_user_memory() writes a single user memory.

  • get_metrics() reads aggregated usage metrics.

  • upsert_sessions() and upsert_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.

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.

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