Examples
- Examples
- Getting Started
- Agents
- Teams
- Workflows
- Applications
- Streamlit Apps
- Evals
Agent Concepts
- Reasoning
- Multimodal
- RAG
- User Control Flows
- Knowledge
- Memory
- Built-in Memory
- Standalone Memory Operations
- Persistent Memory with SQLite
- Custom Memory Creation
- Memory Search
- Agent With Memory
- Agentic Memory
- Agent with Session Summaries
- Multiple Agents Sharing Memory
- Custom Memory
- Multi-User Multi-Session Chat
- Multi-User Multi-Session Chat Concurrent
- Memory References
- Session Summary References
- Mem0 Memory
- DB
- Async
- Hybrid Search
- Storage
- Tools
- Vector Databases
- Context
- Embedders
- Agent State
- Observability
- Miscellaneous
Models
- Anthropic
- AWS Bedrock
- AWS Bedrock Claude
- Azure AI Foundry
- Azure OpenAI
- Cerebras
- Cerebras OpenAI
- Cohere
- DeepInfra
- DeepSeek
- Fireworks
- Gemini
- Groq
- Hugging Face
- IBM
- LM Studio
- LiteLLM
- LiteLLM OpenAI
- Meta
- Mistral
- NVIDIA
- Ollama
- OpenAI
- Perplexity
- Together
- XAI
- Vercel
DB
MongoDB Memory Storage
Code
cookbook/agent_concepts/memory/mongodb_memory.py
Copy
"""
This example shows how to use the Memory class with MongoDB storage.
"""
import asyncio
import os
from agno.agent.agent import Agent
from agno.memory.v2.db.mongodb import MongoMemoryDb
from agno.memory.v2.memory import Memory
from agno.models.openai.chat import OpenAIChat
# Get MongoDB connection string from environment
# Format: mongodb://username:password@localhost:27017/
mongo_url = "mongodb://localhost:27017/"
database_name = "agno_memory"
# Create MongoDB memory database
memory_db = MongoMemoryDb(
connection_string=mongo_url,
database_name=database_name,
collection_name="memories" # Collection name to use in the database
)
# Create memory instance with MongoDB backend
memory = Memory(db=memory_db)
# This will create the collection if it doesn't exist
memory.clear()
# Create agent with memory
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
memory=memory,
enable_user_memories=True,
)
async def run_example():
# Use the agent with MongoDB-backed memory
await agent.aprint_response(
"My name is Jane Smith and I enjoy painting and photography.",
user_id="jane@example.com",
)
await agent.aprint_response(
"What are my creative interests?",
user_id="jane@example.com",
)
# Display the memories stored in MongoDB
memories = memory.get_user_memories(user_id="jane@example.com")
print("Memories stored in MongoDB:")
for i, m in enumerate(memories):
print(f"{i}: {m.memory}")
if __name__ == "__main__":
asyncio.run(run_example())
Usage
1
Create a virtual environment
Open the Terminal
and create a python virtual environment.
Copy
python3 -m venv .venv
source .venv/bin/activate
2
Set environment variables
Copy
export OPENAI_API_KEY=xxx
3
Install libraries
Copy
pip install -U agno openai pymongo
4
Run Example
Copy
python cookbook/agent_concepts/memory/mongodb_memory.py
Was this page helpful?
Assistant
Responses are generated using AI and may contain mistakes.