$vectorSearch is a MongoDB aggregation pipeline stage that retrieves documents whose stored embeddings are similar to a query vector. It supports semantic search, such as finding movie plots related to a phrase even when their wording differs. Create an Atlas Vector Search index on the embedding field before running the stage. section 12.3 section 12.3.1
Listing 12.3 The $vectorSearch aggregation pipeline stage
{
"$vectorSearch": {
"exact": true | false,
"filter": {<filter-specification>},
"index": "<index-name>",
"limit": <number-of-results>,
"numCandidates": <number-of-candidates>,
"path": "<field-to-search>",
"queryVector": [<array-of-numbers>]
}
}
Use the stage prototype to locate its index, embedding field, query vector, result limit, candidate count, search mode, and optional filter. section 12.3
Prepare and tune a query in this order:
- Generate a numerical embedding for the query using the same model used to embed the collection’s data. Text alone is not a query vector; embedding generation may require an external system. section 12.3.1
- Set index to the existing vector search index, path to the stored embedding field, queryVector to the complete embedding array, and limit to the maximum results wanted. section 12.3 section 12.3.1
- Leave exact false for approximate nearest-neighbor search, or set it true for a slower, more precise exact search. For approximate search, increasing numCandidates can improve precision at a processing cost. section 12.3 section 12.8
Find related movie plots
With an indexed plot_embedding field and a complete embedding of “village life,” run db.embedded_movies.aggregate([{ $vectorSearch: { index: "MongoDB-in-Action-VectorSearchIndex", path: "plot_embedding", queryVector: queryEmbedding, numCandidates: 100, exact: false, limit: 10 } }]). Here queryEmbedding stands for the prepared numerical array, not the phrase itself. To narrow the search first, add filter: { $or: [{ genre: "Action" }, { runtime: { $lt: 120 } }] }; both filtered fields must be indexed as filter fields. section 12.3.1 section 12.3.2
Prefiltering reduces the documents considered before similarity search, but its fields and operators have restrictions. Supported filter values include BSON booleans, dates, ObjectIds, strings, and numbers; range comparisons are not supported for ObjectId filter fields. The stage cannot appear in view definitions, $lookup or $unionWith subpipelines, or a $facet stage. section 12.3.2
