> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB Atlas 集成

> 使用 LangChain JavaScript 与 MongoDB Atlas 向量存储集成。

<Tip>
  **兼容性**：仅在 Node.js 上可用。

  您仍然可以通过将 `runtime` 变量设置为 `nodejs` 来创建使用 MongoDB 的 Next.js API 路由，如下所示：

  `export const runtime = "nodejs";`

  更多信息，请参阅 [Next.js 文档中的 Edge 运行时](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes)。
</Tip>

本指南提供了快速入门 MongoDB Atlas [向量存储](/oss/javascript/integrations/vectorstores)的概览。有关所有 `MongoDBAtlasVectorSearch` 功能和配置的详细文档，请前往 [API 参考](https://reference.langchain.com/javascript/langchain-mongodb/MongoDBAtlasVectorSearch)。

## 概览

### 集成详情

| 类                                                                                                                   | 包                                                                        | [Python 支持](https://python.langchain.com/docs/integrations/vectorstores/mongodb_atlas/) |                                                版本                                               |
| :------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------- | :-------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------: |
| [`MongoDBAtlasVectorSearch`](https://reference.langchain.com/javascript/langchain-mongodb/MongoDBAtlasVectorSearch) | [`@langchain/mongodb`](https://www.npmjs.com/package/@langchain/mongodb) |                                            ✅                                            | ![NPM - Version](https://img.shields.io/npm/v/@langchain/mongodb?style=flat-square\&label=%20&) |

## 设置

要使用 MongoDB Atlas 向量存储，您需要配置一个 MongoDB Atlas 集群并安装 `@langchain/mongodb` 集成包。

### 初始集群配置

要创建 MongoDB Atlas 集群，请导航至 [MongoDB Atlas 网站](https://www.mongodb.com/products/platform/atlas-database)，如果您还没有账户，请创建一个。

在提示时创建并命名一个集群，然后在 `Database` 下找到它。选择 `Browse Collections` 并创建一个空白集合或从提供的示例数据中创建一个集合。

**注意：** 对于手动嵌入模式，集群必须是 MongoDB 7.0 或更高版本。自动嵌入模式需要 [MongoDB 8.2 或更高版本](https://www.mongodb.com/docs/atlas/atlas-vector-search/crud-embeddings/create-embeddings-automatic/?interface=driver\&language=nodejs)。

### 创建向量搜索索引

配置集群后，在您的集合上创建一个向量搜索索引。您可以在 [Atlas](https://www.mongodb.com/docs/atlas/atlas-vector-search/tutorials/vector-search-quick-start/)、[Compass](https://www.mongodb.com/docs/compass/indexes/create-vector-search-index/) 或 [MongoDB Shell](https://www.mongodb.com/docs/atlas/atlas-vector-search/tutorials/vector-search-quick-start/?deployment-type=atlas\&embedding=byo\&interface=mongosh) 上执行此操作。索引定义取决于您使用的嵌入模式。

**手动嵌入**（MongoDB 7.0+）：您在客户端嵌入文档并将向量存储在一个字段中。使用以下定义，调整 `numDimensions` 以匹配您的嵌入模型。

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "name": "index_name",
  "type": "vectorSeach",
  "definition": {
    "fields": [
      {
        "numDimensions": 1536,
        "path": "embedding",
        "similarity": "euclidean",
        "type": "vector"
      }
    ]
  }
}
```

**自动嵌入**（MongoDB 8.2+）：MongoDB 使用 [Voyage AI 模型](https://www.mongodb.com/products/platform/ai-search-and-retrieval/models)在服务器端生成嵌入。使用 `autoEmbed` 字段类型并指定模型：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "name": "index_name",
  "type": "vectorSeach",
  "definition": {
    "fields": [
      {
        "type": "autoEmbed",
        "modality": "text",
        "path": "textContent",
        "model": "voyage-4"
      }
    ]
  }
}
```

默认情况下，向量存储从名为 `text` 的文本字段读取，并（在手动模式下）将向量写入名为 `embedding` 的字段。设置 `textKey` 和 `embeddingKey` 以匹配您的索引。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const vectorStore = new MongoDBAtlasVectorSearch(
  embeddings,                  // 在自动嵌入模式下省略
  {
    collection,
    indexName: "index_name",
    textKey: "textContent",    // 存储原始文本的文档字段
    embeddingKey: "embedding", // 匹配 "path"（在自动嵌入模式下省略）
  }
);
```

继续构建索引。

### 嵌入

在**手动嵌入模式**下，您提供一个嵌入模型并在客户端嵌入文档。本指南以 [OpenAI 嵌入](/oss/javascript/integrations/embeddings/openai)为例。您也可以使用[其他支持的嵌入模型](/oss/javascript/integrations/embeddings)。

在**自动嵌入模式**下，MongoDB Atlas 在服务器端处理嵌入生成。不需要客户端嵌入包。

### 安装

<Tabs>
  <Tab title="手动嵌入">
    安装核心包和嵌入提供程序：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm install @langchain/mongodb mongodb @langchain/core @langchain/openai
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/mongodb mongodb @langchain/core @langchain/openai
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/mongodb mongodb @langchain/core @langchain/openai
      ```
    </CodeGroup>
  </Tab>

  <Tab title="自动嵌入">
    只需要核心包和 MongoDB 驱动程序：

    <CodeGroup>
      ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      npm install @langchain/mongodb mongodb @langchain/core
      ```

      ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      yarn add @langchain/mongodb mongodb @langchain/core
      ```

      ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pnpm add @langchain/mongodb mongodb @langchain/core
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### 凭证

完成上述步骤后，从 Mongo 仪表板的 `Connect` 按钮设置 `MONGODB_ATLAS_URI` 环境变量。您还需要数据库名称和集合名称：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
process.env.MONGODB_ATLAS_URI = "your-atlas-URL";
process.env.MONGODB_ATLAS_COLLECTION_NAME = "your-atlas-collection-name";
process.env.MONGODB_ATLAS_DB_NAME = "your-atlas-db-name";
```

如果您使用的是带有 OpenAI 的手动嵌入模式，请同时设置您的 OpenAI 密钥：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

在自动嵌入模式下，不需要额外的 API 密钥——MongoDB Atlas 使用您索引中配置的模型处理嵌入生成。

如果您想获得模型调用的自动跟踪，也可以通过取消注释以下内容来设置您的 [LangSmith](/langsmith/home) API 密钥：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

设置好集群和索引后，初始化您的向量存储。构造函数接受两种形式，具体取决于您使用的是手动嵌入还是自动嵌入。

<Tabs>
  <Tab title="手动嵌入">
    将嵌入实例作为第一个参数传递：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
    import { OpenAIEmbeddings } from "@langchain/openai";
    import { MongoClient } from "mongodb";

    const client = new MongoClient(process.env.MONGODB_ATLAS_URI!);
    const collection = client
      .db(process.env.MONGODB_ATLAS_DB_NAME)
      .collection(process.env.MONGODB_ATLAS_COLLECTION_NAME);

    const embeddings = new OpenAIEmbeddings({
      model: "text-embedding-3-small",
    });

    const vectorStore = new MongoDBAtlasVectorSearch(embeddings, {
      collection,
      indexName: "vector_index", // 默认为 "default"
      textKey: "text",           // 默认为 "text"
      embeddingKey: "embedding", // 默认为 "embedding"
    });
    ```
  </Tab>

  <Tab title="自动嵌入">
    只传递配置对象（不需要嵌入参数）。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
    import { MongoClient } from "mongodb";

    const client = new MongoClient(process.env.MONGODB_ATLAS_URI!);
    const collection = client
      .db(process.env.MONGODB_ATLAS_DB_NAME)
      .collection(process.env.MONGODB_ATLAS_COLLECTION_NAME);

    const vectorStore = new MongoDBAtlasVectorSearch({
      collection,
      indexName: "default", // 必须与您 Atlas 集群中的索引名称匹配
    });
    ```
  </Tab>
</Tabs>

## 管理向量存储

### 向向量存储添加项目

现在您可以将文档添加到向量存储中：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "The powerhouse of the cell is the mitochondria",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "Buildings are made out of brick",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "Mitochondria are made out of lipids",
  metadata: { source: "https://example.com" }
};

const document4: Document = {
  pageContent: "The 2024 Olympics are in Paris",
  metadata: { source: "https://example.com" }
}

const documents = [document1, document2, document3, document4];

await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });
```

<Note>
  添加文档后，需要一段时间才能进行查询。在自动嵌入模式下，此延迟更长，因为 MongoDB 必须在插入后在服务器端生成嵌入。请等到 Atlas 搜索索引报告文档已索引后再进行查询。
</Note>

添加具有与现有文档相同 `id` 的文档将更新现有文档。

### 从向量存储中删除项目

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
await vectorStore.delete({ ids: ["4"] });
```

## 查询向量存储

创建向量存储并添加相关文档后，您很可能希望在链或代理运行期间对其进行查询。

### 直接查询

执行简单相似性搜索的方法如下：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const similaritySearchResults = await vectorStore.similaritySearch("biology", 2);

for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]
```

### 过滤

MongoDB Atlas 支持在其他字段上对结果进行预过滤。它们要求您通过更新最初创建的索引来定义您计划过滤的元数据字段。以下是一个示例：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "fields": [
    {
      "numDimensions": 1024,
      "path": "embedding",
      "similarity": "euclidean",
      "type": "vector"
    },
    {
      "path": "source",
      "type": "filter"
    }
  ]
}
```

上面，`fields` 中的第一个项目是向量索引，第二个项目是您要过滤的元数据属性。属性的名称是 `path` 键的值。因此，上述索引允许我们在名为 `source` 的元数据字段上进行搜索。

然后，在您的代码中，您可以使用 [MQL 查询运算符](https://www.mongodb.com/docs/manual/reference/mql/query-predicates/#alphabetical-list-of-operators)进行过滤。

以下示例说明了这一点：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const filter = {
  preFilter: {
    source: {
      $eq: "https://example.com",
    },
  },
}

const filteredResults = await vectorStore.similaritySearch("biology", 2, filter);

for (const doc of filteredResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]
```

### 返回分数

如果您想执行相似性搜索并接收相应的分数，可以运行：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2, filter)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* [SIM=0.374] The powerhouse of the cell is the mitochondria [{"_id":"1","source":"https://example.com"}]
* [SIM=0.370] Mitochondria are made out of lipids [{"_id":"3","source":"https://example.com"}]
```

### 通过转换为检索器进行查询

您还可以将向量存储转换为[检索器](/oss/javascript/langchain/retrieval)，以便在链中更轻松地使用。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const retriever = vectorStore.asRetriever({
  // 可选过滤器
  filter: filter,
  k: 2,
});
await retriever.invoke("biology");
```

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[
  Document {
    pageContent: 'The powerhouse of the cell is the mitochondria',
    metadata: { _id: '1', source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: 'Mitochondria are made out of lipids',
    metadata: { _id: '3', source: 'https://example.com' },
    id: undefined
  }
]
```

### 用于检索增强生成

有关如何将此向量存储用于检索增强生成 (RAG) 的指南，请参阅以下部分：

* [使用 LangChain 构建 RAG 应用](/oss/javascript/langchain/rag)。
* [代理式 RAG](/oss/javascript/langgraph/agentic-rag)
* [检索文档](/oss/javascript/langchain/retrieval)

## 关闭连接

完成后，请确保关闭客户端实例以避免过度消耗资源：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
await client.close();
```

***

## API 参考

有关所有 `MongoDBAtlasVectorSearch` 功能和配置的详细文档，请前往 [API 参考](https://reference.langchain.com/javascript/langchain-mongodb/MongoDBAtlasVectorSearch)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/vectorstores/mongodb_atlas.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
