You can integrate MongoDB with Google ADK , an open-source Python framework for building AI agents. The integration provides three components:
MongoDbToolset, which provides MongoDB Vector Search and hybrid search tools to agents
MongoDbSessionService, which persists agent sessions, events, and state in MongoDB
MongoDbMemoryService, which stores session events in MongoDB for keyword-based long-term memory recall
Get Started
To complete a tutorial that configures Google ADK to use MongoDB, see Get Started with the MongoDB Google ADK Integration.
Installation
To install Google ADK and the MongoDB dependencies, run the following command:
pip install "google-adk[mongodb]"This command also installs the PyMongo driver. The integration requires PyMongo v4.9 or later.
Usage
This section describes the three components that you can use to integrate MongoDB with Google ADK.
MongoDbToolset
MongoDbToolset is a toolset class that includes the following read-only search tools, which can access a MongoDB database:
mongodb_vector_search: Ranks documents by embedding similaritymongodb_hybrid_search: Combines that similarity ranking with a full-text ranking
Important
Required Indexes
To use the preceding search tools, you must create the indexes described in the Index Guidelines section.
When calling one of these tools, the agent model passes a plain-text query as the tool argument. Both tools embed this text internally, so the model never produces or handles a vector.
To view an example that binds the toolset to your MongoDB database, select the tab corresponding to your preferred connection method:
The following example shows how to use a connection string to configure a toolset:
from google.adk.agents import Agentfrom google.adk.integrations.mongodb import MongoDbToolset
toolset = MongoDbToolset( connection_string="<connection_string>", database_name="products_db",)
agent = Agent( model="gemini-2.5-flash", name="product_search_agent", instruction=( "Search the products collection with your MongoDB tools." ), tools=[toolset],)To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
The following example shows how to use a connection string stored in an environment variable to configure a toolset:
from google.adk.agents import Agentfrom google.adk.integrations.mongodb import MongoDbToolset
toolset = MongoDbToolset( connection_string_env_var="MONGODB_URI", database_name="products_db",)
agent = Agent( model="gemini-2.5-flash", name="product_search_agent", instruction=( "Search the products collection with your MongoDB tools." ), tools=[toolset],)For Atlas Agent Engine deployments, we recommend that you use this parameter instead of connection_string.
For connection options that the toolset doesn't expose, you can use your own pymongo.MongoClient instance instead of a connection string. The following example shows how to use a client to configure a toolset:
from pymongo import MongoClientfrom google.adk.integrations.mongodb import MongoDbToolset
client = MongoClient("<connection_string>")toolset = MongoDbToolset(database_name="products_db", mongo_client=client)
# ... Pass toolset to an agentTo learn more about PyMongo clients, see Create a MongoClient in the PyMongo documentation.
Note
The toolset doesn't take ownership of this client. You are responsible for closing it.
Name the target collection in the agent's instruction, because the model chooses a collection on every call. For the implications this has for the data that the toolset can access, see the Collection Choice section.
Credentials for the embedding model come from Application Default Credentials, Google Cloud's standard mechanism for discovering credentials. Credentials for MongoDB come from the connection string.
Configure Settings
MongoDbToolSettings is a settings class that configures the embedding model, index names, and search limits that MongoDbToolset uses. Pass an instance of this class to the settings parameter of MongoDbToolset to override its defaults, as shown in the following example:
from google.adk.integrations.mongodb import MongoDbToolsetfrom google.adk.integrations.mongodb import MongoDbToolSettings
toolset = MongoDbToolset( connection_string="<connection_string>", database_name="products_db", settings=MongoDbToolSettings(default_limit=8, max_results=20),)Embedding Modes
Before running a vector search, the toolset embeds your query text. Select the Atlas Automated Embedding tab to allow Atlas to embed queries automatically, or select the Google embedding models tab to view the default embedding behavior:
To use Atlas Automated Embedding, set the use_mongodb_auto_embedding parameter to True on the MongoDbToolSettings configuration class. The following example shows this configuration:
from google.adk.integrations.mongodb import MongoDbToolsetfrom google.adk.integrations.mongodb import MongoDbToolSettings
toolset = MongoDbToolset( connection_string="<connection_string>", database_name="products_db", settings=MongoDbToolSettings( use_mongodb_auto_embedding=True, mongodb_auto_embedding_model="voyage-4", # optional ),)With this configuration, the toolset does not make a Google embedding call. Instead, the vector search stage receives the query text, and Atlas generates the embedding with the Voyage AI model configured on the index. The searched field must be indexed as the autoEmbed type.
Tip
Preview Feature
Atlas Automated Embedding is also available as a Preview feature on self-managed deployments. To learn more, see About the autoEmbed Type.
By default, the toolset embeds the query through a Vertex AI embedding model and passes the resulting vector as the queryVector field of the $vectorSearch aggregation stage. The following example shows this default configuration:
from google.adk.integrations.mongodb import MongoDbToolset
toolset = MongoDbToolset( connection_string="<connection_string>", database_name="products_db",)This mode requires Application Default Credentials for the embedding API. The embeddings stored in your documents must come from the same Vertex AI model that embeds the query, which the vertex_ai_embedding_model_name option sets.
Collection Choice
The model chooses the collection on each call, so a toolset bound to a database accesses every collection in that database that has a search index. Set the database_name parameter to a database that contains only data the agent is allowed to read, and store any other data in a separate database.
The tool_filter parameter doesn't restrict which collections the model can access, because it selects whole tools and doesn't receive call arguments. To enforce a collection allowlist, use the before_tool_callback hook instead, which does receive the call arguments:
from google.adk.agents import Agentfrom google.adk.integrations.mongodb import MongoDbToolset
def allow_products_only(tool, args, tool_context): if tool.name.startswith("mongodb_") and args.get("collection_name") != "products": return { "status": "ERROR", "error_details": "Only the products collection may be searched.", } return None
agent = Agent( name="product_search_agent", instruction="Answer questions about products.", tools=[ MongoDbToolset( connection_string="<connection_string>", database_name="products_db", ) ], before_tool_callback=allow_products_only,)If the callback returns a dictionary, ADK never runs the search tool. Instead, it sends that dictionary to the agent as if it were the tool's own output. Returning None allows the search tool to run as normal.
MongoDbSessionService
MongoDbSessionService stores sessions, events, and app-, user-, and session-scoped state in MongoDB. Pass it to a Runner object to configure persistent conversation history for your agent, as shown in the following example:
from google.adk.integrations.mongodb import MongoDbSessionServicefrom google.adk.runners import Runner
session_service = MongoDbSessionService( connection_string="<connection_string>", database_name="my_app",)
runner = Runner( agent=agent, app_name="my_app", session_service=session_service,)Document Layout
MongoDbSessionService stores data in the following collections:
Collection | _id Value | Contents |
|---|---|---|
|
| Session-scoped state in JSON, timestamps, and an optimistic-concurrency revision number |
|
| Full serialized event |
|
| App-scoped state |
|
| User-scoped state |
Google ADK scopes state to the app, a user, or the current session with an app: or user: prefix on the state key. MongoDbSessionService stores each value in the corresponding collection and strips the prefix from the stored key, so a value set with the key app:theme is stored in the app_states collection as theme.
Note
Each collection's state field stores its keys and values as a JSON-encoded string, not as a native MongoDB document. As a result, a state key containing a character that MongoDB forbids in document field names, such as . or $, is stored and retrieved without data loss or corruption.
Concurrency Model
The service's concurrency model depends on your deployment type:
On a replica set, sharded cluster, or Atlas cluster, every multi-document write runs in a transaction, so it commits or aborts atomically.
On a standalone
mongod, or any deployment without transaction support, the service falls back to sequential writes with an optimistic-concurrency revision check on the session document.
Within a single process, a per-session lock prevents concurrent writes to the same session. This lock has no effect across multiple processes, such as when multiple instances of your application write to the same session at the same time.
Across multiple processes, the session document's revision check prevents data corruption. If two writes compete, the write that completes first increments the revision number, and the other write fails its revision check. Your application must catch this failure, reload the session to get its current state, and retry the write.
MongoDbMemoryService
MongoDbMemoryService stores session events in a memory collection and retrieves them by keyword matching. Pass it to a Runner object to configure long-term memory across sessions, as shown in the following example:
from google.adk.integrations.mongodb import MongoDbMemoryServicefrom google.adk.runners import Runner
memory_service = MongoDbMemoryService( connection_string="<connection_string>", database_name="my_app",)
runner = Runner( agent=agent, app_name="my_app", memory_service=memory_service,)The Runner object calls the memory service's add_session_to_memory() method to ingest a session's events into memory. Each ingested event is stored as a memory document in your memories collection, which the memories_collection parameter configures. These documents contain the lowercase keywords extracted from the event's text content.
Considerations
When using the memory service, consider the following behavior:
When you search memory, the service returns documents whose keyword array intersects the query's keywords.
Ingestion is idempotent. If you re-ingest a session, the service overwrites its memories rather than duplicating them.
Retrieval performs a keyword search and does not require an embedding model, Google credentials, or a vector index. As a result, memory retrieval works on any MongoDB deployment.
Index Guidelines
This section describes the indexes required to integrate MongoDB and Google ADK, and it includes recommended indexes for performance improvements.
Required MongoDbToolset Indexes
Each collection that the agent searches requires the following indexes:
MongoDB Vector Search index on the field that stores the embeddings, with the field indexed as the
vectortype. If you use Atlas Automated Embedding, index the field as theautoEmbedtype instead.MongoDB Search index on the field that stores the text to search, if you use the
mongodb_hybrid_searchtool
MongoDbToolset reads these indexes by name and does not create them. To learn how to create these indexes, see Create a MongoDB Vector Search Index and MongoDB Search Index.
Suggested Service Indexes
Most reads and all writes use the _id field, which MongoDB indexes automatically. However, the following read patterns don't use the _id field and require a full collection scan unless you have an index:
Reading a session's events by app, user, and session, sorted by timestamp.
Searching memory by app and user with a match on the keywords array.
By default, MongoDbSessionService and MongoDbMemoryService create the following suggested indexes on first use:
Collection | Index | Indexed Fields and Sort Order |
|---|---|---|
|
|
|
|
|
|
|
|
|
If you set the ensure_indexes parameter to False, the service does not create these suggested indexes.
Note
Index creation is idempotent, so you can safely leave the ensure_indexes parameter set to its default value of True. This parameter requires the MongoDB user to hold the createIndex action on the sessions, events, and memories collections.
Permissions Guidelines
Instead of using a single admin user, we recommend that you use two separate database users to keep privileges scoped to what each component requires.
The following table describes the suggested least-privilege configuration for two database users:
Database User | Used By | Minimum Privileges |
|---|---|---|
Search user (read-only) |
|
|
State user (read-write) |
| * |
Important
The privileges in the preceding table are MongoDB actions, not Atlas built-in roles. To grant them, create a custom role for each user with these actions, scoped to the listed collections.
Additional Resources
To learn more about using Google ADK with MongoDB, see the following resources:
Google ADK GitHub repository