Chat History & MemoryLesson 6

MongoDB Chat Message History

After PostgreSQL, this lesson stores turns in MongoDB instead. RunnableWithMessageHistory stays the same — only get_session_history returns MongoDBChatMessageHistory. Set MONGODB_URL (default mongodb://localhost:27017) and pass session_id in config.

Before you start

Complete PostgreSQL Chat Message History first. Here you swap the storage backend only — chain, template, and invoke stay the same.

PostgreSQL vs MongoDB

Both backends persist history across restarts. PostgreSQL uses SQL rows; MongoDB stores JSON documents — no create_tables step.

PostgreSQL

Rows in chat_history table
One row per message
Query with SQL

MongoDB

Documents per session_id
JSON message payloads
No create_tables step
Same RunnableWithMessageHistory wrapper — only get_session_history returns MongoDBChatMessageHistory instead of PostgresChatMessageHistory.

Install

Activate the venv from Project Setup, then install the MongoDB integration. You also need a MongoDB server — see MongoDB installation or run Docker: docker run -p 27017:27017 mongo.

pip install langchain-mongodb

Connect

Set MONGODB_URL in your .env file. The demo defaults to local MongoDB on port 27017.

# .env — optional; defaults to local MongoDB
MONGODB_URL=mongodb://localhost:27017

Document shape per session:

session_id— e.g. demo-1
{ "type": "human", "data": { "content": "What does the <a> tag do?" } }
{ "type": "ai", "data": { "content": "The <a> tag creates a hyperlink…" } }

Stored by langchain-mongodb — default database on localhost.

Set MONGODB_URL for Atlas or another host. Inspect documents in Compass or mongosh when you need to verify storage.

Each invoke

On each invoke, the wrapper loads prior documents for session_id, runs the chain, then saves the new turn.

Steps inside one invoke (session_id=demo-1):

config

session_id → get_session_history

load

MongoDB collection — prior turns

chain

prompt | model

save

new human + reply → MongoDB

Re-run the script with the same session_id — prior turns load from MongoDB on the next invoke.

get_session_history

Return a MongoDBChatMessageHistory instance for each session_id. The wrapper calls this on every invoke — same interface as PostgreSQL or Redis backends.

import os
from langchain_mongodb import MongoDBChatMessageHistory

MONGODB_URL = os.getenv("MONGODB_URL", "mongodb://localhost:27017")

def get_session_history(session_id: str):
    return MongoDBChatMessageHistory(
        connection_string=MONGODB_URL,
        session_id=session_id,
    )

Wrap and invoke

Same wrapper and invoke call as RunnableWithMessageHistory (In-Memory) — only get_session_history changed.

chain_with_history = RunnableWithMessageHistory(
    chain,
    get_session_history,
    input_messages_key="input",
    history_messages_key="history",
)
config = {"configurable": {"session_id": "demo-1"}}

reply = chain_with_history.invoke(
    {"input": question},
    config=config,
)

The demo script

mongodb_chat_message_history_demo.py runs the same two HTML <a> questions with session_id="demo-1" stored in MongoDB.

mongodb_chat_message_history_demo.py
"""mongodb_chat_message_history_demo.py"""
MongoDBChatMessageHistory(connection_string=…, session_id=…)
RunnableWithMessageHistory(chain, get_session_history, …)
invoke({"input": question}, config=session_id)

Download the code

mongodb_chat_message_history_demo.py

Two HTML questions — MongoDB backend

Download .py
Requires a running MongoDB instance (install MongoDB) and MONGODB_URL in .env. Venv from Project Setup.

Run it

Start MongoDB locally (Docker: docker run -p 27017:27017 mongo), then:

python mongodb_chat_message_history_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> pip install langchain-mongodb
Successfully installed langchain-mongodb …
(.venv) PS C:\projects\langchain-course> python mongodb_chat_message_history_demo.py
Human: What does the HTML <a> tag do?
AI: The <a> tag creates a hyperlink to another page or resource.
Human: What attribute opens the link in a new tab?
AI: Use target="_blank" on the <a> tag.
History stored in MongoDB (mongodb://localhost:27017)
The second answer works because both invokes use the same session_id and MongoDB kept the first exchange.

Quick reference

  • MongoDBChatMessageHistory — from langchain_mongodb; pass connection_string and session_id.
  • MONGODB_URL — defaults to mongodb://localhost:27017; override in .env for Atlas or production.
  • Install: pip install langchain-mongodb.
  • No create_tables call — the integration writes documents on first save.
  • Docs: MongoDBChatMessageHistory API · Message history how-to · RunnableWithMessageHistory.

What's Next

Next: Introduction to Streamlit — install Streamlit and run a starter page before adding LangChain history.