Modern enterprise applications combine traditional document databases with Vector Search to power Retrieval-Augmented Generation (RAG), semantic code search, and contextual recommendation engines without maintaining a separate vector database.
1. Understanding Vector Embeddings in MongoDB
An embedding is a dense mathematical array of floating-point numbers representing the conceptual meaning of text, code, or images.
// Course document stored with dense vector embedding
{
"_id": ObjectId("655f1a9b2c8d4e0012a4b8c1"),
"title": "Mastering Go Concurrency & Goroutines",
"category": "Backend Development",
"summary": "Deep dive into channels, mutexes, select statements, and CSP architecture.",
// 1536-dimensional vector generated via OpenAI text-embedding-3-small
"embedding": [0.0124, -0.0452, 0.0891, -0.0031, /* ... 1536 floats */],
"is_published": true
}
2. Defining the Vector Search Index
In MongoDB Atlas, configure a dedicated vector search index:
{
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine" // "cosine" | "euclidean" | "dotProduct"
},
{
"type": "filter",
"path": "category"
},
{
"type": "filter",
"path": "is_published"
}
]
}
3. Executing a Vector Search Aggregation Pipeline
Using the $vectorSearch pipeline stage, MongoDB uses an HNSW (Hierarchical Navigable Small World) graph algorithm to find the nearest semantic neighbors in milliseconds:
import { MongoClient } from "mongodb";
import OpenAI from "openai";
const openai = new OpenAI();
const client = new MongoClient(process.env.MONGODB_URI);
async function searchCourses(naturalQuery, targetCategory) {
await client.connect();
const db = client.db("learning_platform");
// 1. Convert user's question into a vector
const embeddingResponse = await openai.embeddings.create({
model: "text-embedding-3-small",
input: naturalQuery
});
const queryVector = embeddingResponse.data[0].embedding;
// 2. Query MongoDB using $vectorSearch with pre-filtering
const results = await db.collection("courses").aggregate([
{
$vectorSearch: {
index: "vector_index",
path: "embedding",
queryVector: queryVector,
numCandidates: 150, // Candidate pool for HNSW traversal
limit: 5, // Return top 5 closest matches
filter: {
category: targetCategory,
is_published: true
}
}
},
{
$project: {
title: 1,
summary: 1,
category: 1,
// Expose the similarity score (0.0 to 1.0)
similarity_score: { $meta: "vectorSearchScore" }
}
}
]).toArray();
return results;
}
4. Hybrid Search: Vector + Full-Text BM25
Pure vector search can miss exact product SKUs, error codes, or function names (e.g. searching for ERR_CONNECTION_REFUSED).
Hybrid Search combines Lucene-based text search ($search) with semantic vector search ($vectorSearch) and merges the rankings using Reciprocal Rank Fusion (RRF), delivering the highest possible retrieval precision for LLM context generation.