兼容性 :仅在 Node.js 上可用。您仍然可以通过将 runtime 变量设置为 nodejs 来创建使用 MongoDB 的 Next.js API 路由,如下所示: export const runtime = "nodejs";更多信息,请参阅 Next.js 文档中的 Edge 运行时 。
本指南提供了快速入门 MongoDB Atlas 向量存储 的概览。有关所有 MongoDBAtlasVectorSearch 功能和配置的详细文档,请前往 API 参考 。
集成详情
要使用 MongoDB Atlas 向量存储,您需要配置一个 MongoDB Atlas 集群并安装 @langchain/mongodb 集成包。
初始集群配置
要创建 MongoDB Atlas 集群,请导航至 MongoDB Atlas 网站 ,如果您还没有账户,请创建一个。
在提示时创建并命名一个集群,然后在 Database 下找到它。选择 Browse Collections 并创建一个空白集合或从提供的示例数据中创建一个集合。
注意: 对于手动嵌入模式,集群必须是 MongoDB 7.0 或更高版本。自动嵌入模式需要 MongoDB 8.2 或更高版本 。
创建向量搜索索引
配置集群后,在您的集合上创建一个向量搜索索引。您可以在 Atlas 、Compass 或 MongoDB Shell 上执行此操作。索引定义取决于您使用的嵌入模式。
手动嵌入 (MongoDB 7.0+):您在客户端嵌入文档并将向量存储在一个字段中。使用以下定义,调整 numDimensions 以匹配您的嵌入模型。
{
" name " : "index_name" ,
" type " : "vectorSeach" ,
" definition " : {
" fields " : [
{
" numDimensions " : 1536 ,
" path " : "embedding" ,
" similarity " : "euclidean" ,
" type " : "vector"
}
]
}
}
自动嵌入 (MongoDB 8.2+):MongoDB 使用 Voyage AI 模型 在服务器端生成嵌入。使用 autoEmbed 字段类型并指定模型:
{
" name " : "index_name" ,
" type " : "vectorSeach" ,
" definition " : {
" fields " : [
{
" type " : "autoEmbed" ,
" modality " : "text" ,
" path " : "textContent" ,
" model " : "voyage-4"
}
]
}
}
默认情况下,向量存储从名为 text 的文本字段读取,并(在手动模式下)将向量写入名为 embedding 的字段。设置 textKey 和 embeddingKey 以匹配您的索引。
const vectorStore = new MongoDBAtlasVectorSearch (
embeddings , // 在自动嵌入模式下省略
{
collection ,
indexName : "index_name" ,
textKey : "textContent" , // 存储原始文本的文档字段
embeddingKey : "embedding" , // 匹配 "path"(在自动嵌入模式下省略)
}
) ;
继续构建索引。
在手动嵌入模式 下,您提供一个嵌入模型并在客户端嵌入文档。本指南以 OpenAI 嵌入 为例。您也可以使用其他支持的嵌入模型 。
在自动嵌入模式 下,MongoDB Atlas 在服务器端处理嵌入生成。不需要客户端嵌入包。
安装核心包和嵌入提供程序: npm install @langchain/mongodb mongodb @langchain/core @langchain/openai
只需要核心包和 MongoDB 驱动程序: npm install @langchain/mongodb mongodb @langchain/core
完成上述步骤后,从 Mongo 仪表板的 Connect 按钮设置 MONGODB_ATLAS_URI 环境变量。您还需要数据库名称和集合名称:
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 密钥:
process . env . OPENAI_API_KEY = "YOUR_API_KEY" ;
在自动嵌入模式下,不需要额外的 API 密钥——MongoDB Atlas 使用您索引中配置的模型处理嵌入生成。
如果您想获得模型调用的自动跟踪,也可以通过取消注释以下内容来设置您的 LangSmith API 密钥:
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
实例化
设置好集群和索引后,初始化您的向量存储。构造函数接受两种形式,具体取决于您使用的是手动嵌入还是自动嵌入。
将嵌入实例作为第一个参数传递: 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"
} ) ;
只传递配置对象(不需要嵌入参数)。 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 集群中的索引名称匹配
} ) ;
管理向量存储
向向量存储添加项目
现在您可以将文档添加到向量存储中:
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" ] } ) ;
添加文档后,需要一段时间才能进行查询。在自动嵌入模式下,此延迟更长,因为 MongoDB 必须在插入后在服务器端生成嵌入。请等到 Atlas 搜索索引报告文档已索引后再进行查询。
添加具有与现有文档相同 id 的文档将更新现有文档。
从向量存储中删除项目
await vectorStore . delete ( { ids : [ "4" ] } ) ;
查询向量存储
创建向量存储并添加相关文档后,您很可能希望在链或代理运行期间对其进行查询。
直接查询
执行简单相似性搜索的方法如下:
const similaritySearchResults = await vectorStore . similaritySearch ( "biology" , 2 ) ;
for ( const doc of similaritySearchResults) {
console . log ( `* ${ doc . pageContent } [ ${ JSON . stringify ( doc . metadata , 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 支持在其他字段上对结果进行预过滤。它们要求您通过更新最初创建的索引来定义您计划过滤的元数据字段。以下是一个示例:
{
" fields " : [
{
" numDimensions " : 1024 ,
" path " : "embedding" ,
" similarity " : "euclidean" ,
" type " : "vector"
},
{
" path " : "source" ,
" type " : "filter"
}
]
}
上面,fields 中的第一个项目是向量索引,第二个项目是您要过滤的元数据属性。属性的名称是 path 键的值。因此,上述索引允许我们在名为 source 的元数据字段上进行搜索。
然后,在您的代码中,您可以使用 MQL 查询运算符 进行过滤。
以下示例说明了这一点:
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 ) } ]` ) ;
}
* 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"}]
返回分数
如果您想执行相似性搜索并接收相应的分数,可以运行:
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 ) } ]` ) ;
}
* [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"}]
通过转换为检索器进行查询
您还可以将向量存储转换为检索器 ,以便在链中更轻松地使用。
const retriever = vectorStore . asRetriever ( {
// 可选过滤器
filter : filter ,
k : 2 ,
} ) ;
await retriever . invoke ( "biology" ) ;
[
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) 的指南,请参阅以下部分:
关闭连接
完成后,请确保关闭客户端实例以避免过度消耗资源:
API 参考
有关所有 MongoDBAtlasVectorSearch 功能和配置的详细文档,请前往 API 参考 。
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。