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.

Get Started with the MongoDB Google ADK Integration

You can integrate MongoDB with Google ADK to configure agent search tools and persistent conversation history, both backed by MongoDB. This tutorial uses the MongoDbToolset class to enable a Google ADK agent to search a collection containing penguin data. Then, the tutorial uses the MongoDbSessionService class, allowing the agent to access earlier turns in the conversation.

In this tutorial, you perform the following tasks:

  1. Set up your environment.

  2. Create a collection and a vector search index.

  3. Build an agent that searches your collection.

  4. Add persistent sessions so the agent remembers prior turns.

  5. Run the file and review the output.

Google ADK is an open-source Python framework for building AI agents. This tutorial uses the following Google ADK components to configure an agent and enable MongoDB access:

  • MongoDbToolset: Provides MongoDB Vector Search and hybrid search tools on a MongoDB database

  • MongoDbSessionService: Persists agent sessions, events, and state in MongoDB

This tutorial configures the MongoDbToolset class to use Atlas Automated Embedding, which embeds both your stored documents and your search queries without requiring a separate embedding model or Google credentials.

To complete this tutorial, you must have the following resources:

  • One of the following MongoDB cluster types:

    • An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address is included in your Atlas project's access list.

    • A local Atlas deployment created using Python and Docker. Install atlas-local-lib-py (pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.

    • A MongoDB Community cluster with Search and Vector Search installed.

  • Gemini API key. This tutorial uses a Gemini model, but you can use any supported provider. To learn more, see Models in the Google ADK documentation.

  • Python v3.11 or later.

In this section, you prepare your environment by installing the required dependencies, setting your environment variables, and creating a project file.

1

Run the following commands in your terminal to create a new directory named google-adk-mongodb-project and install the required dependencies:

mkdir google-adk-mongodb-projectcd google-adk-mongodb-projectpip install "google-adk[mongodb]" python-dotenv
2

In your google-adk-mongodb-project directory, create a .env file and add the following code:

GOOGLE_API_KEY="<gemini-api-key>"MONGODB_URI="<connection-string>"

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

Your connection string should use the following format:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

3

In your google-adk-mongodb-project directory, create a file named main.py. Add the following code to this file to load your environment variables and import the required modules:

import osimport timeimport asynciofrom dotenv import load_dotenvfrom pymongo import MongoClientfrom pymongo.operations import SearchIndexModelfrom google.adk.agents import Agentfrom google.adk.integrations.mongodb import ( MongoDbToolset, MongoDbToolSettings, MongoDbSessionService,)from google.adk.runners import Runnerfrom google.genai import types load_dotenv()

In future steps, you add code to this file to create your collection, build your agent, and run it.

In this section, you insert sample documents about penguins into a MongoDB collection and create the MongoDB Vector Search index that Atlas Automated Embedding requires.

1

Add the following code to your main.py file to create a penguins collection in the google_adk_tutorial database, or access it if the collection already exists:

client = MongoClient(os.environ["MONGODB_URI"])collection = client["google_adk_tutorial"]["penguins"]
2

Add the following code to your main.py file to insert five documents describing penguins into your collection. The embeddings field stores the text that Atlas embeds automatically:

collection.insert_many( [ { "title": "Emperor Penguins", "embeddings": "Emperor penguins are the tallest and heaviest of all penguin species, standing up to 4 feet.", }, { "title": "Penguin Habitats", "embeddings": "Penguins are flightless seabirds that live almost exclusively below the equator. Some island-dwellers can be found in warmer climates.", }, { "title": "Penguins of Patagonia", "embeddings": "Patagonia is home to five penguin species: Magellanic, Humboldt, Gentoo, Southern Rockhopper, and King.", }, { "title": "Penguin Diving Depths", "embeddings": "Emperor penguins can dive deeper than any other bird, reaching depths of over 500 meters.", }, { "title": "Penguin Nesting Habits", "embeddings": "Some penguin species mate for life and return to the same nesting site every year.", }, ])
3

Add the following code to your main.py file to create a MongoDB Vector Search index on the embeddings field. The autoEmbed field type instructs Atlas to generate and store embeddings for this field automatically:

search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "autoEmbed", "path": "embeddings", "model": "voyage-4", "modality": "text", } ] }, name="autoembed_index", type="vectorSearch",) collection.create_search_index(model=search_index_model) # Index build time varies with collection size and cluster typeprint("Waiting for the MongoDB Vector Search index to finish building...")time.sleep(60) client.close()

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

In this section, you build an agent that uses the MongoDbToolset class to search your collection. Then, you configure the MongoDbSessionService class to persist the agent's conversation history in MongoDB.

1

Add the following code to your main.py file to bind MongoDbToolset to your database and configure it to use Atlas Automated Embedding:

toolset = MongoDbToolset( connection_string=os.environ["MONGODB_URI"], database_name="google_adk_tutorial", settings=MongoDbToolSettings( use_mongodb_auto_embedding=True, default_embedding_field="embeddings", default_vector_index_name="autoembed_index", ),)

Because the use_mongodb_auto_embedding option is set to True, the toolset sends query text to Atlas as plain text instead of calling a Google embedding model.

2

Add the following code to your main.py file to create an agent that uses a Gemini model and your toolset:

root_agent = Agent( model="gemini-2.5-flash", name="penguin_facts_agent", description="Answers questions about penguins.", instruction=( "Search the penguins collection with your MongoDB" " tools to answer questions about penguins. Remember" " what the user has told you earlier in the" " conversation." ), tools=[toolset],)
3

Add the following code to your main.py file to configure the MongoDbSessionService class and pass it, along with your agent, to a Runner object:

session_service = MongoDbSessionService( connection_string=os.environ["MONGODB_URI"], database_name="google_adk_tutorial",) runner = Runner( agent=root_agent, app_name="google_adk_tutorial", session_service=session_service,)

By default, MongoDbSessionService creates the indexes recommended for its use, unless you set the ensure_indexes parameter to False. To learn more, see Index Guidelines in the Google ADK reference.

4

Add the following code to your main.py file to create a session, then send two messages to the agent through that session:

async def ask(runner, session_id, text): content = types.Content(role="user", parts=[types.Part(text=text)]) async for event in runner.run_async( user_id="tutorial_user", session_id=session_id, new_message=content, ): if event.is_final_response() and event.content: print(f"\n[user]: {text}") print(f"[agent]: {event.content.parts[0].text}") async def main(): session = await session_service.create_session( app_name="google_adk_tutorial", user_id="tutorial_user", ) await ask( runner, session.id, "How deep can emperor penguins dive?" ) await ask( runner, session.id, "What was the first thing I asked you?" ) asyncio.run(main())

Because both calls use the same session_id value, MongoDbSessionService loads the first turn's events before the agent responds to the second message. If you create a new session for the second call, the agent has no record of the first turn.

To run the main.py file, run the following command from your google-adk-mongodb-project directory:

python main.py

If the command runs successfully, the output resembles the following:

Waiting for the MongoDB Vector Search index to finish building... [user]: How deep can emperor penguins dive?[agent]: Emperor penguins can dive deeper than any other bird,reaching depths of over 500 meters. [user]: What was the first thing I asked you?[agent]: The first thing you asked me was about how deep emperorpenguins can dive.

To learn more about MongoDbToolset, MongoDbSessionService, and MongoDbMemoryService, including their full parameter and method reference, see Integrate MongoDB with Google ADK.

To learn more about Google ADK, see the adk-python GitHub repository.