> ## 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 Python 集成 MongoDBAtlasHybridSearchRetriever。

> MongoDB [Atlas](https://www.mongodb.com/docs/atlas/) 是一个完全托管的云数据库，支持 AWS、Azure 和 GCP。它原生支持向量搜索、全文搜索（BM25）和混合搜索，可基于您的 MongoDB 文档数据。

`MongoDBAtlasHybridSearchRetriever` 结合向量搜索和全文搜索，使用 reciprocity rank fusion（RRF）算法从 Atlas 集合返回最相关的文档。若无需向量索引，`MongoDBAtlasFullTextSearchRetriever` 使用 Atlas 搜索的 Lucene（BM25）分析器进行关键词检索。

所有检索器都继承自 `BaseRetriever` 并包含在 `langchain-mongodb` 包中。您可将 [MongoDB Atlas 向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/mongodb_atlas.md) 强转为 `.as_retriever()`。当需要混合搜索或纯全文搜索时，建议使用专用检索器类。

本指南帮助您入门 MongoDB Atlas [检索器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)。所有 `MongoDBAtlasHybridSearchRetriever` 功能和配置的详细文档，请参考 [API 参考](https://reference.langchain.com/python/langchain-mongodb/retrievers/MongoDBAtlasHybridSearchRetriever)。

### 整合细节

## 配置

您需要一个已启用 Atlas 搜索的运行中 MongoDB Atlas 集群。若无，请通过 [Atlas 控制台](https://www.mongodb.com/cloud/atlas/register) 创建集群。

`MongoDBAtlasHybridSearchRetriever` 需要 target 集合上两个搜索索引：

* 一个 **向量搜索索引** 用于语义召回
* 一个 **全文搜索索引** 用于关键词召回

请参考下方 [创建索引](#创建索引) 或在 Atlas 控制台手动创建索引。

若需启用查询级自动追踪，请设置您的 [LangSmith](https://docs.langchain.com/langsmith/home) API 密钥：

```python theme={null}
import getpass
import os

os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

### 安装

安装 `langchain-mongodb`。以下示例也使用了 Voyage AI 嵌入模型：

```bash pip theme={null}
pip install -qU langchain-mongodb langchain-voyageai
```

```bash uv theme={null}
uv add langchain-mongodb langchain-voyageai
```

### 配置

设置 Atlas 连接字符串并打开集合句柄：

```python theme={null}
import getpass
import os

from pymongo import MongoClient

if not os.environ.get("MONGODB_ATLAS_URI"):
    os.environ["MONGODB_ATLAS_URI"] = getpass.getpass("Enter your MongoDB Atlas URI: ")

client = MongoClient(os.environ["MONGODB_ATLAS_URI"])
collection = client["<db_name>"]["<collection_name>"]
```

### 创建索引

在启用混合搜索前，需为集合创建向量搜索索引和全文搜索索引。匹配 `dimensions` 与嵌入模型（`voyage-4-lite` 使用 1024 维度）：

```python theme={null}
from langchain_mongodb import MongoDBAtlasVectorSearch
from langchain_mongodb.index import create_fulltext_search_index
from langchain_voyageai import VoyageAIEmbeddings  # swap in any embeddings class

embeddings = VoyageAIEmbeddings(model="voyage-4-lite")

vector_store = MongoDBAtlasVectorSearch(
    collection=collection,
    embedding=embeddings,
    index_name="vector_index",
)

# Create the vector search index (runs asynchronously on Atlas)
vector_store.create_vector_search_index(
    dimensions=1024,
    wait_until_complete=60,
)

# Create the full-text search index on the text field
create_fulltext_search_index(
    collection=collection,
    field="text",
    index_name="search_index",
    wait_until_complete=60,
)
```

更多索引选项请参考 [MongoDB Atlas 向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/mongodb_atlas.md) 指南。

## 实例化

### 混合搜索

`MongoDBAtlasHybridSearchRetriever` 通过 RRF 融合向量与关键词结果。增加 `vector_penalty` 或 `fulltext_penalty` 可降低该渠道权重：

```python theme={null}
from langchain_mongodb.retrievers import MongoDBAtlasHybridSearchRetriever

retriever = MongoDBAtlasHybridSearchRetriever(
    vectorstore=vector_store,
    search_index_name="search_index",
    k=5,
    vector_penalty=60.0,
    fulltext_penalty=60.0,
)
```

### 全文搜索

`MongoDBAtlasFullTextSearchRetriever` 执行 BM25 关键词搜索且无需向量索引：

```python theme={null}
from langchain_mongodb.retrievers import MongoDBAtlasFullTextSearchRetriever

ft_retriever = MongoDBAtlasFullTextSearchRetriever(
    collection=collection,
    search_index_name="search_index",
    search_field="text",
    k=5,
)
```

## 使用

```python theme={null}
docs = retriever.invoke("What is MongoDB Atlas?")
```

## 在链中调用

```python theme={null}
from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

prompt = ChatPromptTemplate.from_template(
    "Answer the question based only on the following context:\n\n{context}\n\nQuestion: {question}"
)

llm = ChatAnthropic(model="claude-sonnet-4-6")

chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

chain.invoke("What is MongoDB Atlas?")
```

## API 参考

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

全文搜索请参考 [`MongoDBAtlasFullTextSearchRetriever`](https://reference.langchain.com/python/langchain-mongodb/retrievers/MongoDBAtlasFullTextSearchRetriever)。

***

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


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