Documentation
¶
Overview ¶
Package mongodb exposes MongoDB Atlas Vector Search through the Core vector-store capability interfaces. Documents are stored as ordinary BSON documents (`{_id, content, metadata, embedding}`); retrieval runs the `$vectorSearch` aggregation stage. Documents containing media are rejected before indexing I/O because this adapter persists document text and metadata only.
Metadata numbers use BSON integers when integral and representable as int64, otherwise doubles only when their decimal value survives JSON round-tripping. Unrepresentable values are rejected before writing rather than rounded.
Requirements: MongoDB Atlas (vector search isn't available on self-hosted Community / Enterprise — it's an Atlas-only feature). The store uses the v2 official driver (go.mongodb.org/mongo-driver/v2).
Vector similarity functions: SimilarityCosine / SimilarityEuclidean / SimilarityDotProduct. The chosen value is recorded in the Atlas Vector Search index definition.
Indexes. Atlas Vector Search indexes are NOT regular MongoDB indexes; they're managed via the Search Indexes API and live on dedicated Atlas search nodes. The store creates one automatically under StoreConfig.InitializeSchema = true, including any metadata fields enumerated in StoreConfig.MetadataFieldsToFilter as typed `filter` paths.
Filter visitor produces MongoDB query-document syntax — `{"metadata.author": {"$eq": "Alice"}}`, `{"$and": [...]}`, `{"$nor": [...]}` for NOT, and an anchored `{"$regex": "^...$"}` for LIKE — anchored because LIKE matches the whole value, and without the "i" option because it is case-sensitive. The result feeds the `filter` field of `$vectorSearch`.
Search pipeline:
{$vectorSearch: {...}}, {$addFields: {score: {$meta: "vectorSearchScore"}}},
{$match: {score: {$gte: minScore}}}
Candidate pool. numCandidates sizes the priority queue the search fills, so Atlas requires it to be at least the requested result count and at most MaxNumCandidates. StoreConfig.NumCandidates is a recall floor the store raises to cover TopK; a TopK above the ceiling is refused rather than sent.
Upsert acknowledgment. One bulk write reports MatchedCount for the replacements that found an existing document and UpsertedCount for those that inserted one; Index requires their sum to cover the batch. An unacknowledged write concern (w: 0) is rejected rather than reported as success, because MongoDB then answers with no reply at all and the driver's counts carry no information.
See https://www.mongodb.com/docs/atlas/atlas-vector-search/.
Index ¶
- Constants
- type DocumentCollection
- type Similarity
- type Store
- func (s *Store) DeleteIDs(ctx context.Context, ids []string) (err error)
- func (s *Store) DeleteWhere(ctx context.Context, expr filter.Predicate) (err error)
- func (s *Store) Index(ctx context.Context, request *vectorstore.IndexRequest) (err error)
- func (s *Store) Search(ctx context.Context, req *vectorstore.SearchRequest) (response *vectorstore.SearchResponse, err error)
- type StoreConfig
Constants ¶
const ( DefaultVectorIndexName = "vector_index" DefaultEmbeddingPath = "embedding" DefaultContentField = "content" DefaultMetadataField = "metadata" DefaultNumCandidates = 200 )
Exported defaults keep constructor behavior visible and overridable.
const MaxNumCandidates = 10000
MaxNumCandidates is Atlas's ceiling for the $vectorSearch numCandidates field, and so the largest TopK the store can serve.
const Provider = "MongoDB"
Provider is the stable backend name for host-side attribution.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DocumentCollection ¶ added in v0.16.0
type DocumentCollection interface {
BulkWrite(
ctx context.Context,
models []mongo.WriteModel,
opts ...options.Lister[options.BulkWriteOptions],
) (*mongo.BulkWriteResult, error)
Aggregate(
ctx context.Context,
pipeline any,
opts ...options.Lister[options.AggregateOptions],
) (*mongo.Cursor, error)
DeleteMany(
ctx context.Context,
filter any,
opts ...options.Lister[options.DeleteManyOptions],
) (*mongo.DeleteResult, error)
SearchIndexes() mongo.SearchIndexView
}
DocumentCollection is the MongoDB surface the store uses: the batched upsert, the aggregation that runs $vectorSearch, the deletion both delete paths share, and the search-index view schema initialization needs. A mongo.Collection satisfies it. Naming only these four keeps the store's own write accounting checkable without an Atlas cluster.
type Similarity ¶
type Similarity string
Similarity selects the vector similarity function written into the Atlas Vector Search index definition.
const ( // SimilarityCosine — cosine similarity. Default. SimilarityCosine Similarity = "cosine" // SimilarityEuclidean — Euclidean (L2) distance. SimilarityEuclidean Similarity = "euclidean" // SimilarityDotProduct — dot product (best for normalized // embeddings). SimilarityDotProduct Similarity = "dotProduct" )
func (Similarity) String ¶
func (s Similarity) String() string
func (Similarity) Valid ¶
func (s Similarity) Valid() bool
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store implements vector-store capabilities with MongoDB Atlas Vector Search.
func NewStore ¶
func NewStore(ctx context.Context, config StoreConfig) (*Store, error)
NewStore performs schema setup during construction, which is why it takes a context: a store returned before its collection and search index exist would fail on the first index rather than at wiring, where the misconfiguration actually is.
func (*Store) DeleteIDs ¶
DeleteIDs removes documents by their _id — `DeleteMany({_id: {$in: ids}})`. An empty slice is a no-op; unknown ids are silently ignored (idempotent). Implements vectorstore.IDDeleter.
func (*Store) DeleteWhere ¶
func (*Store) Index ¶
func (s *Store) Index(ctx context.Context, request *vectorstore.IndexRequest) (err error)
Index embeds documents and bulk-upserts them by _id.
func (*Store) Search ¶
func (s *Store) Search(ctx context.Context, req *vectorstore.SearchRequest) (response *vectorstore.SearchResponse, err error)
Search runs the $vectorSearch aggregation and returns the matching documents above the configured MinScore threshold.
type StoreConfig ¶
type StoreConfig struct {
// Collection is the MongoDB collection that holds the documents.
// Required.
Collection DocumentCollection
// VectorIndexName is the Atlas Vector Search index name. It must
// match an existing index (or one created by InitializeSchema).
// Optional: defaults to [DefaultVectorIndexName].
VectorIndexName string
// EmbeddingPath is the field that holds the document embedding.
// Optional: defaults to [DefaultEmbeddingPath] ("embedding").
EmbeddingPath string
// ContentField is the field that stores the original text.
// Optional: defaults to [DefaultContentField].
ContentField string
// MetadataField is the sub-document field that holds metadata.
// Optional: defaults to [DefaultMetadataField]. Metadata is always isolated
// in this sub-document so user keys cannot collide with storage fields.
MetadataField string
// MetadataFieldsToFilter pre-declares the metadata keys that
// should be indexed as filter fields in the Atlas search index.
// Filtering on a metadata field requires the field to be listed
// here when InitializeSchema is true.
MetadataFieldsToFilter []string
// EmbeddingModel produces vectors for the documents. Required.
EmbeddingModel embedding.Model
// DocumentBatcher batches documents before upsert. Required.
DocumentBatcher vectorstore.Batcher
// Dimensions is the embedding width written into a new search-index
// definition. When zero and InitializeSchema is true, the store probes
// EmbeddingModel.
Dimensions int
// Similarity selects the vector similarity function. Optional:
// defaults to [SimilarityCosine].
Similarity Similarity
// NumCandidates controls the recall/perf tradeoff of the Atlas
// $vectorSearch stage. It is a floor: a search never considers fewer
// candidates than the results it must return. Optional: defaults to
// [DefaultNumCandidates] (200), and must not exceed [MaxNumCandidates].
NumCandidates int
// InitializeSchema, when true, creates the Atlas vector-search
// index if it doesn't already exist. Requires a connected Atlas
// cluster.
InitializeSchema bool
}
StoreConfig contains configuration options for the MongoDB Atlas Vector Search store.
func (StoreConfig) Validate ¶
func (s StoreConfig) Validate() error