> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.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` 来在 Next.js 中创建使用 MongoDB 的 API 路由，如下所示：
>
> `export const runtime = "nodejs";`
>
> 有关更多信息，请参阅 [Next.js 文档中的边缘运行时](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes)。

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

## 概述

### 集成细节

| 类 | 包 | [PY 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/mongodb_atlas.md) | 版本 |
| :- | :- | :-: | :-: |
| [`MongoDBAtlasVectorSearch`](https://reference.langchain.com/javascript/langchain-mongodb/MongoDBAtlasVectorSearch) | [`@langchain/mongodb`](https://www.npmjs.com/package/@langchain/mongodb) | ✅ | ![NPM - 版本](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={null}
{
  "name": "index_name",
  "type": "vectorSearch",
  "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={null}
{
  "name": "index_name",
  "type": "vectorSearch",
  "definition": {
    "fields": [
      {
        "type": "autoEmbed",
        "modality": "text",
        "path": "textContent",
        "model": "voyage-4"
      }
    ]
  }
}
```

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

```typescript theme={null}
const vectorStore = new MongoDBAtlasVectorSearch(
  embeddings,                  // omit in auto embedding mode
  {
    collection,
    indexName: "index_name",
    textKey: "textContent",    // document field where raw text is stored
    embeddingKey: "embedding", // matches "path" (omit in auto embedding mode)
  }
);
```

继续构建索引。

### 嵌入

在 **手动嵌入模式**中，您提供一个嵌入模型并在客户端嵌入文档。本指南以 [OpenAI 嵌入](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/openai.md) 作为示例。您还可以使用 [其他支持的嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。

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

### 安装

> [tab] Manual embedding
>
> 安装核心包和嵌入提供程序：
>
> ```bash npm theme={null}
> npm install @langchain/mongodb mongodb @langchain/core @langchain/openai
> ```
>
> ```bash yarn theme={null}
> yarn add @langchain/mongodb mongodb @langchain/core @langchain/openai
> ```
>
> ```bash pnpm theme={null}
> pnpm add @langchain/mongodb mongodb @langchain/core @langchain/openai
> ```

> [tab] Automated embedding
>
> 仅需要核心包和 MongoDB 驱动程序：
>
> ```bash npm theme={null}
> npm install @langchain/mongodb mongodb @langchain/core
> ```
>
> ```bash yarn theme={null}
> yarn add @langchain/mongodb mongodb @langchain/core
> ```
>
> ```bash pnpm theme={null}
> pnpm add @langchain/mongodb mongodb @langchain/core
> ```

### 凭证

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

```typescript theme={null}
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={null}
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

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

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

```typescript theme={null}
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

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

> [tab] Manual embedding
>
> 将嵌入实例作为第一个参数传递：
>
> ```typescript theme={null}
> 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", // Defaults to "default"
>   textKey: "text",           // Defaults to "text"
>   embeddingKey: "embedding", // Defaults to "embedding"
> });
> ```

> [tab] Automated embedding
>
> 仅传递配置对象（不需要嵌入参数）。
>
> ```typescript theme={null}
> 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", // Must match the index name in your Atlas cluster
> });
> ```

## 管理向量存储

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

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

```typescript theme={null}
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 搜索索引报告文档已索引之前不要查询。

使用相同的 `id` 添加文档将更新现有文档。

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

```typescript theme={null}
await vectorStore.delete({ ids: ["4"] });
```

## 查询向量存储

当您的向量存储已经创建，并且相关的文档已经添加后，您很可能希望在您的链或智能体运行期间查询它。

### 直接查询

执行简单的相似度搜索可以按以下方式完成：

```typescript theme={null}
const similaritySearchResults = await vectorStore.similaritySearch("biology", 2);

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

```text theme={null}
* 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={null}
{
  "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={null}
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={null}
* 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={null}
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={null}
* [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"}]
```

### 将其转换为检索器进行查询

您还可以将向量存储转换为[检索器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)，以便在您的链中更轻松地使用。

```typescript theme={null}
const retriever = vectorStore.asRetriever({
  // Optional filter
  filter: filter,
  k: 2,
});
await retriever.invoke("biology");
```

```javascript theme={null}
[
  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 应用](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/rag.md)。
* [Agentic RAG](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/agentic-rag.md)
* [检索文档](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)

## 关闭连接

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

```typescript theme={null}
await client.close();
```

***

## API 参考

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

***

> 官方原文：[src/oss/javascript/integrations/vectorstores/mongodb\_atlas.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/vectorstores/mongodb_atlas.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.