MongoDB 벡터 저장소
그만큼MongoDBVector클래스는 다음을 사용하여 벡터 검색을 제공합니다.MongoDB 아틀라스 벡터 검색. MongoDB 컬렉션 내에서 효율적인 유사성 검색 및 메타데이터 필터링이 가능합니다.
설치설치에 대한 직접 링크
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mongodb@latest
pnpm add @mastra/mongodb@latest
yarn add @mastra/mongodb@latest
bun add @mastra/mongodb@latest
사용예사용예에 대한 직접 링크
import { MongoDBVector } from '@mastra/mongodb'
const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})
사용자 정의 포함 필드 경로사용자 정의 포함 필드 경로에 대한 직접 링크
중첩된 필드 구조에 임베딩을 저장해야 하는 경우(예: 기존 MongoDB 컬렉션과 통합하기 위해)embeddingFieldPath option:
import { MongoDBVector } from '@mastra/mongodb'
const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
})
생성자 옵션생성자 옵션에 대한 직접 링크
id:
uri:
dbName:
options?:
embeddingFieldPath?:
행동 양식행동 양식에 대한 직접 링크
connect()connect에 대한 직접 링크
MongoDB 서버에 대한 연결을 설정합니다. 처음 사용할 때 자동으로 호출되지만 필요한 경우 명시적으로 호출할 수 있습니다.
await store.connect()
createIndex()createindex에 대한 직접 링크
MongoDB에 새로운 벡터 인덱스(컬렉션)를 생성합니다.
indexName:
dimension:
metric?:
filterFields?:
metadata.<field>). Queries that filter only on declared fields are pushed directly into $vectorSearch instead of pre-filtering candidate _ids, avoiding the 16 MB BSON limit on large result sets. Filters that reference an undeclared field, or use an operator $vectorSearch does not support, fall back to the pre-filter automatically.collectionName?:
indexName.searchIndexName?:
${indexName}_vector_index.allowWrites?:
upsert, updateVector, deleteVector, deleteVectors) on a bring-your-own collection. By default a BYO index is read-only: the store never modifies or deletes caller-owned operational documents. Ignored for managed collections, which are always writable. The policy is persisted with the index registration and survives restarts.waitForIndexReady()waitforindexready에 대한 직접 링크
생성 후 인덱스가 준비될 때까지 기다립니다. 작업을 수행하기 전에 인덱스가 준비되었는지 확인해야 할 때 유용합니다.
indexName:
timeoutMs?:
checkIntervalMs?:
upsert()upsert에 대한 직접 링크
컬렉션에 벡터와 해당 메타데이터를 추가하거나 업데이트합니다. BYOD(Bring-Your-Own) 색인에서는 다음이 필요합니다.allowWrites: true at createIndex() 시점에 수행됩니다. BYO 컬렉션은 기본적으로 읽기 전용이기 때문입니다.
indexName:
vectors:
metadata?:
ids?:
documents?:
query()query에 대한 직접 링크
선택적 메타데이터 필터링을 사용하여 유사한 벡터를 검색합니다.
indexName:
queryVector:
topK?:
filter?:
metadata field)documentFilter?:
includeVector?:
numCandidates?:
metadataMode?:
'field' (default) projects the managed metadata/document fields, and filter fields are matched against the metadata subdocument. 'document' returns the full source document as metadata — use for bring-your-own operational collections whose documents have their own shape — and filter fields are matched against the **root** document (no metadata. prefix). The embedding field is omitted from metadata by default (to avoid payload bloat); set includeVector: true to retain it in metadata and also expose it as a top-level vector.createSearchIndex()createsearchindex에 대한 직접 링크
인덱스를 뒷받침하는 컬렉션에 Atlas Search(BM25/full-text) 인덱스를 프로비저닝하고 이를 텍스트 검색 인덱스로 기록합니다.textQuery() and hybridQuery() will target.
관리형 컬렉션과 직접 가져오는 컬렉션:
- 에 대한managed index (created without
collectionName),createIndex()already provisions a dynamic full-text index named${collectionName}_search_index(covering all string fields).createSearchIndex()is therefore only needed when you want a field-restricted mapping or a custom index name. - 에 대한bring-your-own index (created with
collectionName),createIndex()doesn't auto-create any full-text index. EnablingtextQuery()/hybridQuery()을 호출자 소유의 운영 컬렉션에서 사용하는 것은 명시적으로 활성화해야 합니다. 을 호출하여createSearchIndex()을 명시적으로 호출하여 비용이 청구되는 텍스트 인덱스를 프로비저닝하세요. 호출하기 전에는textQuery()/hybridQuery()은 존재하지 않는 인덱스를 쿼리하는 대신 명확한 오류를 발생시킵니다.
명명:
- 언제
fieldsis provided without an explicitsearchIndexName, the field-mapped index is created under a distinct default name (${collectionName}_${indexName}_search_fields_index, 논리적 인덱스마다 고유함)을 사용하므로 관리형 컬렉션에서 자동 생성된 동적 인덱스와 충돌하여 조용히 무시되는 일이 없습니다. 이 고유 인덱스는 텍스트 검색 인덱스로 유지되므로textQuery()/hybridQuery()use the restricted mapping automatically. - 언제
searchIndexName이 제공되면 지정된 이름을 그대로 사용하고 유지합니다.textQuery()/hybridQuery()은 유지된 이름을 자동으로 확인합니다. 각 호출에서 해당 을 통해 이름을 재정의할 수도 있습니다.searchIndexName/textSearchIndexNameparameters.
indexName:
fields?:
searchIndexName?:
fields is provided and this is omitted, a distinct default name that is unique per logical index is used, so the field mapping is not shadowed by the auto-created dynamic index and two logical indexes on the same collection do not collide.waitUntilReady?:
waitForSearchIndexReady() explicitly if you prefer to await separately.await store.createSearchIndex({
indexName: 'precedents',
fields: ['note', 'description'],
})
필드 매핑된 인덱스 이름에는 논리 인덱스가 포함됩니다.indexName, 따라서 동일한 컬렉션의 두 논리적 인덱스에는 서로 다른 텍스트 인덱스가 생성됩니다. 을 다시 생성하면 same logical index with different fields still requires dropping the existing index first (IndexAlreadyExists).
waitForSearchIndexReady()waitforsearchindexready에 대한 직접 링크
인덱스의 전체 텍스트(BM25) 검색 인덱스가 READY가 될 때까지 기다립니다.waitForIndexReady() polls only the vectorSearch index; createSearchIndex() 은 Atlas Search 전문 검색 인덱스가 아직 빌드 중인 동안 반환되므로, 즉시 textQuery()/hybridQuery() can intermittently fail. Call this (or pass waitUntilReady: true to createSearchIndex())을 사용하면 확인된 텍스트 인덱스가 READY 상태를 보고할 때까지 대기합니다.
indexName:
searchIndexName?:
timeoutMs?:
checkIntervalMs?:
await store.createSearchIndex({ indexName: 'precedents', fields: ['note'] })
await store.waitForSearchIndexReady({ indexName: 'precedents' })
textQuery()textquery에 대한 직접 링크
Atlas 검색 색인에 대해 전체 텍스트(BM25) 검색을 실행합니다. 기본적으로 이 인덱스에 대해 기록된 텍스트 검색 인덱스를 대상으로 합니다(createSearchIndex(), or the dynamic ${collectionName}_search_index auto-created by createIndex()). Pass searchIndexName to target a specific index for this call.
여기에 메타데이터 필터(예:hybridQuery()) are applied via a $match stage. For the vector branch of hybridQuery(), filters on fields not declared via filterFields 에서 인덱스를 생성할 때 지정한 항목은 후보 로 투명하게 구체화됩니다. _ids (the same fallback query() uses), so undeclared-field filters don't error.
indexName:
query:
paths:
topK?:
filter?:
metadata field)metadataMode?:
'field' (default) projects the managed metadata/document fields. 'document' returns the full source document as metadata.searchIndexName?:
createSearchIndex() / createIndex().const results = await store.textQuery({
indexName: 'precedents',
query: 'shell company offshore',
paths: ['note'],
topK: 10,
})
hybridQuery()hybridquery에 대한 직접 링크
MongoDB의 서버 측을 사용하여 벡터 유사성과 전체 텍스트 결과를 융합하는 하이브리드 검색을 실행합니다.$rankFusion. MongoDB 8.0 이상이 필요하며 8.1부터 일반적으로 사용할 수 있습니다. 8.0.x에서는 활성화를 위해 MongoDB 지원 요청이 필요할 수 있으며 Atlas 8.0.x처럼 활성화된 환경에서 실행됩니다. 전문 검색 인덱스가 반드시 있어야 합니다. 관리형 인덱스에는 자동으로 생성되지만, 자체 컬렉션을 사용하는 경우에는 을 호출해야 합니다. createSearchIndex() first (opt-in).
indexName:
queryVector:
query:
paths:
topK?:
filter?:
weights?:
numCandidates?:
metadataMode?:
'field' (default) projects the managed metadata/document fields. 'document' returns the full source document as metadata.textSearchIndexName?:
createSearchIndex() / createIndex().const results = await store.hybridQuery({
indexName: 'precedents',
queryVector: embedding,
query: 'shell company offshore',
paths: ['note'],
topK: 10,
weights: { vector: 1, text: 1.5 }, // Favor text matches
})
hybridQuery()MongoDB >= 8.0이 필요합니다.$rankFusion 단계입니다. 이 단계는 8.1부터 일반적으로 사용할 수 있습니다. 8.0.x에서는 활성화를 위해 MongoDB 지원 요청이 필요할 수 있으며 Atlas 8.0.x처럼 활성화된 환경에서 실행됩니다. 이전 버전을 실행 중이거나 $rankFusion isn't enabled on your 8.0.x deployment, use query() and textQuery() separately and merge the results client-side.
describeIndex()describeindex에 대한 직접 링크
인덱스(컬렉션)에 대한 정보를 반환합니다.
indexName:
보고:
interface IndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct'
}
deleteIndex()deleteindex에 대한 직접 링크
벡터 인덱스를 삭제합니다. 동작은 인덱스 생성 방법에 따라 다릅니다.
- 관리형 인덱스(없이 생성됨
collectionName): 전체 컬렉션과 그 안의 모든 데이터를 삭제합니다. - 지참 색인(다음으로 생성됨
collectionName): Atlas vectorSearch 인덱스와, 을 통해 프로비저닝된 경우createSearchIndex(), 함께 제공되는 전문 검색 인덱스를 삭제합니다. 호출자의 운영 컬렉션과 그 문서는 보존됩니다. 이 저장소는 자신이 생성하지 않은 컬렉션을 절대 삭제하지 않습니다.
BYO 분류는 인덱스가 생성될 때 지속적으로 기록되므로 다른 프로세스(예: 설정 작업으로 생성되고 나중에 장기 서비스로 삭제되는 인덱스)에서도 올바르게 적용됩니다. 항상 합격하세요logical index name (the indexName used at createIndex), not the physical collection name.
indexName:
listIndexes()listindexes에 대한 직접 링크
다음을 나열합니다.logical Mastra index names (the indexName values passed to createIndex)이며 물리적 컬렉션 이름이 아닙니다. 데이터가 운영 컬렉션에 있는 자체 인덱스의 경우 물리적 컬렉션 이름 대신 논리적 인덱스 이름이 반환됩니다. 이 값은 에 그대로 다시 전달할 수 있습니다. deleteIndex() / describeIndex(). 영구 메타데이터가 도입되기 전에 생성된 관리형 인덱스도 해당 를 통해 계속 검색됩니다. ${name}_vector_index 검색 인덱스입니다. 내부 레지스트리 컬렉션은 목록에 절대 표시되지 않습니다.
보고:Promise<string[]>
updateVector()updatevector에 대한 직접 링크
ID 또는 메타데이터 필터를 기준으로 단일 벡터를 업데이트합니다. 어느 하나id or filter must be provided, but not both.
자체 컬렉션 가져오기는 기본적으로 읽기 전용입니다.
upsert(),updateVector(),deleteVector(), anddeleteVectors()은 로 생성되지 않은 BYO 인덱스에서 USER 범주 오류를 발생시킵니다.allowWrites: true. See Indexing an existing collection.
indexName:
id?:
filter?:
update:
update.vector?:
update.metadata?:
deleteVector()deletevector에 대한 직접 링크
ID별로 인덱스에서 특정 벡터 항목을 삭제합니다.
indexName:
id:
deleteVectors()deletevectors에 대한 직접 링크
ID 또는 메타데이터 필터를 기준으로 여러 벡터를 삭제합니다. 어느 하나ids or filter must be provided, but not both.
indexName:
ids?:
filter?:
disconnect()disconnect에 대한 직접 링크
MongoDB 클라이언트 연결을 닫습니다. 매장 이용이 끝나면 전화해야 합니다.
응답 유형응답 유형에 대한 직접 링크
쿼리 결과는 다음 형식으로 반환됩니다.
interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}
오류 처리오류 처리에 대한 직접 링크
상점에서는 포착할 수 있는 입력된 오류를 발생시킵니다.
try {
await store.query({
indexName: 'my_collection',
queryVector: queryVector,
})
} catch (error) {
// Handle specific error cases
if (error.message.includes('Invalid collection name')) {
console.error(
'Collection name must start with a letter or underscore and contain only valid characters.',
)
} else if (error.message.includes('Collection not found')) {
console.error('The specified collection does not exist')
} else {
console.error('Vector store error:', error.message)
}
}
기존 컬렉션 색인화기존 컬렉션 색인화에 대한 직접 링크
관리형 컬렉션을 사용하는 대신 기존 운영 컬렉션에 벡터 인덱스를 생성할 수 있습니다. 이는 MongoDB 데이터베이스에 이미 존재하는 문서에 벡터 검색 기능을 추가하려는 경우에 유용합니다.
import { MongoDBVector } from '@mastra/mongodb'
const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})
// Create a vector index on an existing 'transactions' collection
await store.createIndex({
indexName: 'precedents',
dimension: 1024,
collectionName: 'transactions', // Use existing collection
searchIndexName: 'txn_vec_idx', // Custom search index name
})
// Wait for the index to be ready
await store.waitForIndexReady({ indexName: 'precedents' })
// Query using document mode to get full source documents
const hits = await store.query({
indexName: 'precedents',
queryVector: embeddings,
topK: 5,
metadataMode: 'document', // Returns full document as metadata
})
// hits[0].metadata now contains all fields from the source document
console.log(hits[0].metadata.amount, hits[0].metadata.customField)
// Full-text / hybrid search on a BYO collection is opt-in: provision the text index first.
await store.createSearchIndex({ indexName: 'precedents', fields: ['note'] })
중요 사항:
- 컬렉션은 이미 존재해야 하며 다음과 같은 문서를 포함해야 합니다.
embeddingfield (or the customembeddingFieldPathyou configured) - 사용할 때 컬렉션이 생성되거나 삭제되지 않습니다.
collectionName - BYO 인덱스는 기본적으로 읽기 전용입니다.
upsert(),updateVector(),deleteVector(), anddeleteVectors()은 호출자 소유의 운영 문서를 변경하는 대신 명확한 오류를 발생시킵니다. 저장소가 컬렉션에 임베딩을 쓰거나 컬렉션에서 문서를 삭제하도록 허용하려면 을 사용하여 명시적으로 활성화하세요.createIndex({ ..., allowWrites: true }). 이 정책은 유지되며 재시작 후에도 적용됩니다. 이전 버전에서 플래그 없이 작성된 항목은 읽기 전용으로 취급됩니다(안전 우선으로 실패). - 사용
metadataMode: 'document'을 쿼리할 때 사용하여 전체 원본 문서를 로 가져옵니다.metadata - ~ 안에
'document'mode the embedding is omitted frommetadataby default; passincludeVector: true을 사용하여 이를 유지하고 최상위 수준의 로도 노출합니다.vector) - 필터링 중
'document'mode operates on root document fields, 중첩되지 않음metadata.subdocument.filter: { lane: 'fraud' }matches the top-levellane운영 문서의 필드(기본'field'mode, bare fields are rewritten tometadata.<field>for managed collections). Both the pushdown and$matchfallback paths honor this. - 토종의
ObjectId_ids are supported.운영 컬렉션은 일반적으로 다음 사항을 핵심으로 합니다.ObjectId; query results coerce_idto a string (theQueryResult.idcontract), anddeleteVector()/updateVector()/deleteVectors()accept that string and match the underlyingObjectIddocument. Managed collections (string_ids) are unaffected. - BYO 컬렉션에 대한 전체 텍스트 및 하이브리드 검색은 다음과 같습니다.opt-in: no full-text index is auto-created, so call
createSearchIndex()beforetextQuery()/hybridQuery(). The full-text index builds asynchronously. CallwaitForSearchIndexReady()(or passwaitUntilReady: true) before an immediate text/hybrid query. deleteIndex()BYO 인덱스에서는 벡터 인덱스(및 텍스트 인덱스가 생성된 경우)가 삭제되지만preserves the collection and its documents
모범 사례모범 사례에 대한 직접 링크
- 최적의 쿼리 성능을 위해 필터에 사용되는 인덱스 메타데이터 필드입니다.
- 예상치 못한 쿼리 결과를 방지하려면 메타데이터에서 일관된 필드 이름 지정을 사용하세요.
- 효율적인 검색을 위해 인덱스 및 컬렉션 통계를 정기적으로 모니터링합니다.
- 기존 컬렉션을 색인화할 때 모든 문서에 필수 사항이 있는지 확인하세요.
embeddingfield.
사용예사용예에 대한 직접 링크
벡터 임베딩MongoDBvector-embeddings-with-mongodb에 대한 직접 링크
임베딩은 Memory에서 사용되는 숫자 벡터입니다.semanticRecall 를 사용하여 키워드가 아닌 의미를 기준으로 관련 메시지를 검색합니다.
MongoDB Atlas 벡터 검색은 프로덕션 용도로 권장됩니다. 자체 호스팅 배포의 경우 벡터 검색을 다음과 같이 사용할 수 있습니다.local Atlas deployments via the Atlas CLI.
이 설정에서는 로컬 임베딩 Model인 FastEmbed를 사용하여 벡터 임베딩을 생성합니다.
이것을 사용하려면 설치하세요.@mastra/fastembed:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastembed@latest
pnpm add @mastra/fastembed@latest
yarn add @mastra/fastembed@latest
bun add @mastra/fastembed@latest
Agent에 다음을 추가합니다.
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
import { fastembed } from '@mastra/fastembed'
export const mongodbAgent = new Agent({
id: 'mongodb-agent',
name: 'mongodb-agent',
instructions:
'You are an AI agent with the ability to automatically recall memories from previous interactions.',
model: 'openai/gpt-5.6-sol',
memory: new Memory({
storage: new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
vector: new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
},
generateTitle: true, // generates descriptive thread titles automatically
},
}),
})
VoyageAI를 사용한 벡터 임베딩VoyageAI를 사용한 벡터 임베딩에 대한 직접 링크
VoyageAI는 검색 작업에 최적화된 특화된 임베딩 Model을 제공합니다. VoyageAI는 다중 모드 임베딩을 위해 MongoDB Atlas와도 통합되어 있습니다.
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/voyageai@latest
pnpm add @mastra/voyageai@latest
yarn add @mastra/voyageai@latest
bun add @mastra/voyageai@latest
기본 사용 예:
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
import { voyage } from '@mastra/voyageai'
export const mongodbVoyageAgent = new Agent({
id: 'mongodb-voyage-agent',
name: 'MongoDB VoyageAI Agent',
instructions: 'You are an AI agent with semantic recall powered by VoyageAI and MongoDB.',
model: 'openai/gpt-5.6-sol',
memory: new Memory({
storage: new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
vector: new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
embedder: voyage, // VoyageAI's default model (voyage-3.5, 1024 dimensions)
options: {
lastMessages: 10,
semanticRecall: {
topK: 5,
messageRange: 2,
},
},
}),
})
특수 Model, 다중 모드 임베딩 및 검색 최적화를 포함한 자세한 VoyageAI 임베딩 예제는 다음을 참조하세요.VoyageAI embeddings documentation.