Engineering · 2026-11-22 · 3 min read
Explore how to integrate embeddings and Vector Search features directly into MongoDB to build intelligent semantic search applications.
In the era of artificial intelligence (AI) and machine learning, modern applications increasingly require semantic understanding capabilities rather than traditional keyword-based search. Embeddings (vector representations) are the key to solving this problem.
Embeddings are arrays of floating-point numbers (vectors) representing text, images, or data in a multidimensional space. Objects with similar meanings are placed close to each other in this vector space. Vector Search allows us to find the nearest vectors based on mathematical distance (such as Cosine Similarity or Euclidean Distance).
To build a semantic search system, we need to convert raw data into vectors via an embedding model, then store and query them using a vector-supported database like MongoDB.
MongoDB provides the Atlas Vector Search feature, allowing direct storage of vector fields within familiar JSON documents and efficient execution of k-NN (k-Nearest Neighbors) searches through the HNSW (Hierarchical Navigable Small World) algorithm.
Before storing in MongoDB, we need to use a model like OpenAI text-embedding-3-small or open-source models on Hugging Face to convert text into vectors.
{
"_id": "ObjectId('...')",
"title": "Giới thiệu về MongoDB",
"content": "MongoDB là cơ sở dữ liệu NoSQL hướng tài liệu...",
"embedding": [0.0123, -0.0456, 0.0789, "..."]
}On MongoDB Atlas, we define a Search Index with the data type set to vectorSearch to index the field containing vectors:
{
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
}
]
}Use the Aggregation Pipeline with the $vectorSearch stage to perform the search:
const pipeline = [
{
$vectorSearch: {
index: "vector_index",
path: "embedding",
queryVector: [0.0111, -0.0222, "..."],
numCandidates: 100,
limit: 5
}
},
{
$project: {
title: 1,
content: 1,
score: { $meta: "vectorSearchScore" }
}
}
];
const results = await db.collection("articles").aggregate(pipeline).toArray();Dimensions: A larger number of dimensions may yield higher accuracy but comes at the cost of increased storage space and computation time.
NumCandidates: This parameter determines the number of candidate documents evaluated during approximate nearest neighbor (ANN) search. Balance is needed between latency and recall.
Hybrid Search: Combine traditional Full-Text Search and Vector Search to achieve optimal results.
Integrating Vector Search directly into MongoDB helps engineers simplify system architecture without needing to maintain an additional standalone vector database. This optimizes data management and system synchronization.
Keep exploring