Skip to main content

Short-term memory with MongoDB Atlas

还没翻译译自英文(docs.langchain.com)本页 14 段都还没译

Short-term memory lets your agent remember previous interactions within a single thread or conversation. This guide shows how to use MongoDB Atlas as the persistent checkpointer backend.

MongoDB stores conversation state as documents in a collection, so threads can resume across process restarts and deployments.

Tip

Need to remember information across conversations? Use long-term memory with MongoDB Atlas to store and recall data across different threads and sessions.

Setup

Installation

npm install @langchain/langgraph-checkpoint-mongodb mongodb
yarn add @langchain/langgraph-checkpoint-mongodb mongodb
pnpm add @langchain/langgraph-checkpoint-mongodb mongodb

Credentials

Set your Atlas connection string:

export MONGODB_ATLAS_URI="your-atlas-connection-string"

If you want automated tracing of your model calls, set your LangSmith API key:

export LANGSMITH_API_KEY="your-api-key"
export LANGSMITH_TRACING="true"

Usage

Create a MongoClient, construct MongoDBSaver, and call setup() once so indexes exist. There is no MongoDBSaver.fromConnString helper.

import { createAgent, tool } from "langchain";
import { MongoDBSaver } from "@langchain/langgraph-checkpoint-mongodb";
import { MongoClient } from "mongodb";
import * as z from "zod";

const getUserInfo = tool(() => "No user profile on file.", {
  name: "get_user_info",
  description: "Look up information about the current user.",
  schema: z.object({}),
});

const MONGODB_ATLAS_URI = process.env.MONGODB_ATLAS_URI;
if (!MONGODB_ATLAS_URI) {
  throw new Error("MONGODB_ATLAS_URI is required");
}

const client = new MongoClient(MONGODB_ATLAS_URI);
const checkpointer = new MongoDBSaver({ client });
await checkpointer.setup();

const agent = createAgent({
  model: "anthropic:claude-sonnet-4-6",
  tools: [getUserInfo],
  checkpointer,
});

const threadConfig = { configurable: { thread_id: "1" } };
let result = await agent.invoke(
  { messages: [{ role: "user", content: "Hi! My name is Bob." }] },
  threadConfig,
);
console.log(result.messages.at(-1)?.content);

result = await agent.invoke(
  { messages: [{ role: "user", content: "What's my name?" }] },
  threadConfig,
);
console.log(result.messages.at(-1)?.content);

await client.close();

Next steps