You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中如何复用Mongo Atlas存储的Langchain向量嵌入以降低OpenAI成本?

解决方案:复用Mongo Atlas中已保存的向量,避免重复生成嵌入

完全可行,你不需要每次服务启动都调用fromDocuments()重新生成嵌入。LangChain的MongoDBAtlasVectorSearch支持直接从已存在的Mongo集合加载向量存储,具体实现如下:

核心逻辑

先检查Mongo集合中是否已有向量数据:

  • 若集合为空,再调用fromDocuments()生成并保存嵌入
  • 若已有数据,直接初始化MongoDBAtlasVectorSearch实例加载现有向量

代码实现

// 先检查集合内是否已有向量文档
const documentCount = await this.collection.countDocuments();

if (documentCount === 0) {
  // 无数据时,生成嵌入并保存到Mongo
  this.vectorStore = await MongoDBAtlasVectorSearch.fromDocuments(docs, embeddings, {
    collection: this.collection
  });
} else {
  // 已有数据,直接加载向量存储
  this.vectorStore = new MongoDBAtlasVectorSearch(embeddings, {
    collection: this.collection,
    indexName: "vector_index", // 替换为你在Mongo Atlas创建的向量索引名称
    textKey: "pageContent", // 存储文档原文的字段名,默认是pageContent
    embeddingKey: "embedding" // 存储向量的字段名,默认是embedding
  });
}

额外注意事项

  1. 向量索引要求:确保你已经在Mongo Atlas中为embedding字段创建了正确的向量索引,否则无法正常进行向量检索
  2. 添加新文档:后续如果有新的PDF需要加入系统,直接调用addDocuments()方法即可,无需重新生成全部嵌入:
    await this.vectorStore.addDocuments(newPdfDocs);
    

内容的提问来源于stack exchange,提问作者Carlos Muentes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 21:30:07