MSMuhammad Shahid

Engineering notes

Optimizing Vector Search Performance in MongoDB vs. PostgreSQL

By Muhammad Shahid · · 20 min read

Quick answer

On the same 100,000 vectors and the same laptop, pgvector answered in about 3 ms (median) with recall@10 of 0.987 at ef_search = 100, while MongoDB Vector Search answered in about 6.6 ms with recall 0.999 at numCandidates = 200. Both use HNSW and built their index in about 15 seconds. pgvector was faster per query here; MongoDB reached near-perfect recall at its recommended setting. Tuning ef_search and numCandidates matters more than the choice of database.

Key facts
Data100,000 vectors, 384 dimensions, cosine, 200 queries, k = 10
PostgreSQLPostgreSQL 17 + pgvector 0.8.7, HNSW m = 16, ef_construction = 64
MongoDBAtlas Local 9.0.4 ($vectorSearch, mongot), filter field indexed
MachineApple M1 Pro, Docker, one client, sequential queries
CodeTypeScript, mongodb 7.8 driver, pg 8 + pgvector; all numbers from one run

Most comparisons of MongoDB Atlas Vector Search vs PostgreSQL pgvector performance quote vendor numbers on different hardware. This article runs both on the same machine, with the same 100,000 vectors and the same 200 questions, measures recall and latency at several settings, and shows every line of code so you can rerun it on your own data. The numbers below come from one run on an Apple M1 Pro with both databases in Docker. They show how the two behave and how to tune them; they are not a promise about your production cluster.

Which is faster for vector search, MongoDB or PostgreSQL?

In this test, pgvector was faster per query: about 3 ms median against about 6.6 to 7.3 ms for MongoDB. MongoDB reached higher recall at its recommended setting: 0.999 with numCandidates = 200, where pgvector needed ef_search = 200 to reach 0.998. Both indexes took about 15 seconds to build. The honest summary is that both are fast enough for most applications at this size, and the bigger differences are architectural: where the index lives, how filters work and how writes become searchable.

How vector search works in each database

Where the vector index lives: in PostgreSQL the HNSW index sits next to the table in the same process; in MongoDB the HNSW index lives in mongot, a separate search process kept in sync with mongod
Same algorithm, different place in the system.

Both use HNSW (Hierarchical Navigable Small World), a graph index that finds close neighbours without comparing the query with every vector. The difference is where it runs. In PostgreSQL, pgvector stores the index next to the table, inside the database process, so a vector query is ordinary SQL: it can join, filter and run inside a transaction, and a new row is searchable as soon as its transaction commits.

In MongoDB, the vector index lives in mongot, the search process behind Atlas Search and Vector Search. mongod stores documents; mongot keeps its own index in sync with them and answers the $vectorSearch stage. That separation lets Atlas run search on dedicated search nodes, but it also means a document becomes searchable shortly after it is written, not at the same instant, and every query makes one extra hop.

What was tested, and how

PostgreSQL + pgvectorMongoDB Vector Search
VersionPostgreSQL 17, pgvector 0.8.7MongoDB Atlas Local 9.0.4 (mongod + mongot)
IndexHNSW, vector_cosine_ops, m = 16, ef_construction = 64vectorSearch index, cosine, category as a filter field
Query setting triedef_search 40, 100, 200numCandidates 100, 200, 400
Clientnode-postgres with pgvector typesOfficial MongoDB Node.js driver 7.8

The data is 100,000 synthetic, normalised 384-dimension vectors in 200 clusters, which behaves more like real embeddings than uniform random noise, plus a category field with 10 values. The 200 queries come from the same distribution but are not in the data. Recall@10 compares each answer with the exact top 10, computed by brute force in the benchmark. Latency is the time for one query from the Node.js client, after 20 warm-up queries, with one client sending queries one at a time. Each pgvector query also runs BEGIN, a SET LOCAL and COMMIT, so its latency includes those round trips.

Results: recall, latency and build time

Scatter chart of recall at 10 against median latency: pgvector points sit around 3 milliseconds with recall from 0.921 to 0.998; MongoDB points sit around 6.6 to 7.3 milliseconds with recall from 0.994 to 1.0
Each point is one setting; higher and further left is better.
SettingRecall@10p50 latencyp95 latency
pgvector ef_search = 40 (default)0.9213.0 ms6.0 ms
pgvector ef_search = 1000.9872.9 ms5.9 ms
pgvector ef_search = 2000.9983.4 ms8.0 ms
pgvector, filter on category, ef_search = 100, iterative scan0.9834.1 ms6.3 ms
MongoDB numCandidates = 1000.9947.3 ms14.9 ms
MongoDB numCandidates = 2000.9996.6 ms7.3 ms
MongoDB numCandidates = 4001.0006.8 ms7.5 ms
MongoDB, filter on category, numCandidates = 2001.0008.1 ms9.4 ms
Loading and indexingPostgreSQL + pgvectorMongoDB
Load 100,000 rows or documents (batches of 1,000)13.4 s5.4 s
Build the vector index14.8 sabout 15 s until queryable
Size on disktable 156 MB, HNSW index 195 MBnot measured

What the numbers mean

  • The default ef_search is low. At pgvector's default of 40, recall was 0.921: almost one in twelve true neighbours was missing. Raising it to 100 cost nothing measurable here and lifted recall to 0.987. Check this setting before you blame the embeddings.
  • Latency was flat across settings. On 100,000 vectors, a wider search added well under a millisecond in both systems. At this size the cost of a query is mostly fixed overhead (network round trips, planning, the extra hop to the search process), not graph traversal.
  • MongoDB's guidance holds. MongoDB recommends numCandidates of at least 20 times limit. At 200 for a limit of 10, recall was 0.999.
  • Filters did not hurt recall in either system, as long as pgvector used iterative scans. More on that below.
  • Loading was faster into MongoDB in this setup, while index builds took about the same time.
# PostgreSQL 17 with pgvector. --shm-size matters: parallel HNSW builds need shared memory
docker run -d --name vec-pg --shm-size=2g -e POSTGRES_PASSWORD=postgres -p 5432:5432 pgvector/pgvector:pg17

# MongoDB with Vector Search (mongod and mongot) in one container
docker run -d --name vec-mongo -p 27017:27017 mongodb/mongodb-atlas-local:latest
mkdir vector-bench && cd vector-bench && npm init -y && npm pkg set type=module
npm install mongodb pg pgvector
npm install -D typescript tsx @types/node @types/pg
import pg from "pg";
import pgvector from "pgvector/pg";

export const pool = new pg.Pool({
  connectionString: process.env.PG_URL,
  onConnect: async (client) => {
    await pgvector.registerTypes(client);
  },
});

// Uses a plain client: the pool registers the vector type on connect, which fails until the extension exists.
export async function createPgSchema(dims: number) {
  const client = new pg.Client({ connectionString: process.env.PG_URL });
  await client.connect();
  try {
    await client.query("CREATE EXTENSION IF NOT EXISTS vector");
    await client.query(
      "CREATE TABLE IF NOT EXISTS items (id integer PRIMARY KEY, category smallint NOT NULL, embedding vector(" +
        dims + ") NOT NULL)",
    );
  } finally {
    await client.end();
  }
}

// Build the HNSW index after bulk loading: it is much faster than inserting into an existing index.
export async function createPgIndex() {
  await pool.query("SET maintenance_work_mem = '1GB'");
  await pool.query("CREATE INDEX IF NOT EXISTS items_embedding_hnsw ON items USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64)");
  await pool.query("CREATE INDEX IF NOT EXISTS items_category ON items (category)");
  await pool.query("ANALYZE items");
}

export interface Hit {
  id: number;
  score: number;
}

// Top-k by cosine distance. efSearch trades speed for recall; a category filter uses iterative scans
// so a narrow filter still returns k rows.
export async function pgSearch(vector: number[], k: number, efSearch: number, category?: number): Promise<Hit[]> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query("SET LOCAL hnsw.ef_search = " + Number(efSearch));
    if (category !== undefined) await client.query("SET LOCAL hnsw.iterative_scan = relaxed_order");
    const where = category !== undefined ? "WHERE category = $3 " : "";
    const params: unknown[] = [pgvector.toSql(vector), k];
    if (category !== undefined) params.push(category);
    const { rows } = await client.query<Hit>(
      "SELECT id, 1 - (embedding <=> $1) AS score FROM items " + where + "ORDER BY embedding <=> $1 LIMIT $2",
      params,
    );
    await client.query("COMMIT");
    return rows;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

Three details matter. First, the schema is created with a plain client, because the pool registers the vector type on every new connection and that fails until the extension exists. Second, the HNSW index is built after the bulk load, with a generous maintenance_work_mem; inserting into an existing HNSW index row by row is much slower. Third, every query runs in a short transaction so SET LOCAL can change hnsw.ef_search, and for filtered queries hnsw.iterative_scan, for that query only.

One trap appeared during the benchmark. pgvector builds HNSW indexes in parallel using shared memory, and a default Docker container has only 64 MB of it, so the build failed:

-- default Docker container (/dev/shm is 64 MB), maintenance_work_mem = 1GB, 100,000 rows
CREATE INDEX ON t USING hnsw (e vector_cosine_ops);
ERROR:  could not resize shared memory segment "/PostgreSQL.2758897714" to 1070632384 bytes: No space left on device

Starting the container with --shm-size=2g fixed it. On a normal server this rarely bites, but in containers and some managed environments, keep maintenance_work_mem below the shared memory available.

import { MongoClient, type Collection } from "mongodb";

export const mongo = new MongoClient(process.env.MONGO_URL ?? "mongodb://localhost:27017/?directConnection=true");

export interface Item {
  _id: number;
  category: number;
  embedding: number[];
}

export const items = (): Collection<Item> => mongo.db("bench").collection<Item>("items");

// A vector search index, with category indexed as a filter field so it can be pre-filtered.
export async function createMongoIndex(dims: number) {
  await items().createSearchIndex({
    name: "embedding_index",
    type: "vectorSearch",
    definition: {
      fields: [
        { type: "vector", path: "embedding", numDimensions: dims, similarity: "cosine" },
        { type: "filter", path: "category" },
      ],
    },
  });
  // The index builds in the background: wait until it can serve queries.
  while (true) {
    const [index] = (await items().listSearchIndexes("embedding_index").toArray()) as { queryable?: boolean }[];
    if (index?.queryable) return;
    await new Promise((r) => setTimeout(r, 1000));
  }
}

export interface Hit {
  id: number;
  score: number;
}

// Top-k with $vectorSearch. numCandidates trades speed for recall, like ef_search in pgvector.
export async function mongoSearch(vector: number[], k: number, numCandidates: number, category?: number): Promise<Hit[]> {
  const docs = await items()
    .aggregate<Hit>([
      {
        $vectorSearch: {
          index: "embedding_index",
          path: "embedding",
          queryVector: vector,
          numCandidates,
          limit: k,
          ...(category !== undefined && { filter: { category: { $eq: category } } }),
        },
      },
      { $project: { _id: 0, id: "$_id", score: { $meta: "vectorSearchScore" } } },
    ])
    .toArray();
  return docs;
}

The index definition lists the vector field with its dimensions and similarity, and category as a filter field: only fields declared this way can be used in the filter of $vectorSearch. Index creation returns immediately and the index builds in the background, so the code polls listSearchIndexes until queryable is true; querying earlier returns nothing. The query uses numCandidates for the size of the candidate list, limit for the results, and projects the similarity with $meta: "vectorSearchScore". The local Atlas image used here runs the same $vectorSearch stage as Atlas, without a cloud account.

The benchmark harness

// Same data, same queries, same machine: pgvector HNSW vs MongoDB Atlas Local $vectorSearch.
import pgvector from "pgvector/pg";
import { pool, createPgSchema, createPgIndex, pgSearch } from "./pg-search";
import { mongo, items, createMongoIndex, mongoSearch } from "./mongo-search";
import { writeFileSync } from "node:fs";

const N = Number(process.env.N ?? 100000), DIMS = 384, K = 10, Q = 200, CLUSTERS = 200, CATEGORIES = 10;

// Seeded random numbers so every run uses the same data.
let seed = 42;
const rand = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296);
const gauss = () => Math.sqrt(-2 * Math.log(rand() + 1e-12)) * Math.cos(2 * Math.PI * rand());
const normalize = (v: number[]) => { const n = Math.hypot(...v); return v.map((x) => x / n); };
const centers = Array.from({ length: CLUSTERS }, () => Array.from({ length: DIMS }, gauss));
const sample = () => { const c = centers[Math.floor(rand() * CLUSTERS)]; return normalize(c.map((x) => x + gauss() * 0.9)); };

const data = Array.from({ length: N }, (_, i) => ({ id: i, category: i % CATEGORIES, embedding: sample() }));
const queries = Array.from({ length: Q }, () => sample());
const qCategory = (i: number) => i % CATEGORIES;

const dot = (a: number[], b: number[]) => { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; };
function exact(q: number[], category?: number) {
  const scored: [number, number][] = [];
  for (const d of data) if (category === undefined || d.category === category) scored.push([d.id, dot(q, d.embedding)]);
  return new Set(scored.sort((a, b) => b[1] - a[1]).slice(0, K).map((s) => s[0]));
}
const pct = (xs: number[], p: number) => { const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]; };

async function measure(name: string, run: (q: number[], i: number) => Promise<{ id: number }[]>, truth: Set<number>[]) {
  for (let i = 0; i < 20; i++) await run(queries[i], i); // warm-up
  const lat: number[] = []; let found = 0, returned = 0;
  for (let i = 0; i < Q; i++) {
    const t = performance.now(); const hits = await run(queries[i], i); lat.push(performance.now() - t);
    returned += hits.length; found += hits.filter((h) => truth[i].has(h.id)).length;
  }
  const r = { name, recall: +(found / (Q * K)).toFixed(3), p50: +pct(lat, 50).toFixed(2), p95: +pct(lat, 95).toFixed(2), avgReturned: +(returned / Q).toFixed(1) };
  console.log(JSON.stringify(r)); return r;
}

async function main() {
  const out: any = { n: N, dims: DIMS, k: K, queries: Q, results: [] };
  console.log("ground truth...");
  const truth = queries.map((q) => exact(q));
  const truthF = queries.map((q, i) => exact(q, qCategory(i)));

  // ---- PostgreSQL + pgvector
  await createPgSchema(DIMS);
  await pool.query("TRUNCATE items");
  await pool.query("DROP INDEX IF EXISTS items_embedding_hnsw");
  let t = performance.now();
  for (let i = 0; i < N; i += 1000) {
    const batch = data.slice(i, i + 1000), vals: unknown[] = [], rows: string[] = [];
    batch.forEach((d, j) => { rows.push("($" + (j * 3 + 1) + ",$" + (j * 3 + 2) + ",$" + (j * 3 + 3) + ")"); vals.push(d.id, d.category, pgvector.toSql(d.embedding)); });
    await pool.query("INSERT INTO items (id, category, embedding) VALUES " + rows.join(","), vals);
  }
  out.pgLoadS = +((performance.now() - t) / 1000).toFixed(1);
  t = performance.now(); await createPgIndex(); out.pgIndexS = +((performance.now() - t) / 1000).toFixed(1);
  const sizes = await pool.query("SELECT pg_size_pretty(pg_relation_size('items')) AS t, pg_size_pretty(pg_relation_size('items_embedding_hnsw')) AS i");
  out.pgSize = sizes.rows[0];
  console.log("pg load", out.pgLoadS, "s, index", out.pgIndexS, "s", sizes.rows[0]);
  for (const ef of [40, 100, 200]) out.results.push(await measure("pgvector ef_search=" + ef, (q) => pgSearch(q, K, ef), truth));
  out.results.push(await measure("pgvector filter ef_search=100 iterative", (q, i) => pgSearch(q, K, 100, qCategory(i)), truthF));

  // ---- MongoDB Atlas Local
  await mongo.connect();
  await items().drop().catch(() => {});
  t = performance.now();
  for (let i = 0; i < N; i += 1000) await items().insertMany(data.slice(i, i + 1000).map((d) => ({ _id: d.id, category: d.category, embedding: d.embedding })));
  out.mongoLoadS = +((performance.now() - t) / 1000).toFixed(1);
  t = performance.now(); await createMongoIndex(DIMS); out.mongoIndexS = +((performance.now() - t) / 1000).toFixed(1);
  console.log("mongo load", out.mongoLoadS, "s, index", out.mongoIndexS, "s");
  for (const nc of [100, 200, 400]) out.results.push(await measure("mongodb numCandidates=" + nc, (q) => mongoSearch(q, K, nc), truth));
  out.results.push(await measure("mongodb filter numCandidates=200", (q, i) => mongoSearch(q, K, 200, qCategory(i)), truthF));

  writeFileSync("results.json", JSON.stringify(out, null, 2));
  await pool.end(); await mongo.close();
}
main().catch((e) => { console.error(e); process.exit(1); });
export PG_URL=postgres://postgres:postgres@localhost:5432/postgres
export MONGO_URL="mongodb://localhost:27017/?directConnection=true"
N=100000 npx tsx src/bench.ts   # writes results.json

The harness generates the same seeded data for both databases, computes the exact answers by brute force, loads and indexes each database, then runs every setting with 20 warm-up queries and 200 measured ones. Change N, the dimensions or the cluster spread to match your data, or better, replace the generator with a sample of your real embeddings and real queries: recall depends heavily on how your vectors are distributed.

Tuning recall and speed

Table of tuning knobs: ef_search in pgvector matches numCandidates in MongoDB; build parameters, filtering, exact search and quantization are compared side by side
The same dials with different names.

hnsw.ef_search and numCandidates do the same job: they set how many candidates the search keeps while walking the graph. Higher means better recall and slightly more work. Tune them on a sample of real queries with exact answers, the way this benchmark does, and pick the lowest value that meets your recall target. Build-time settings (m and ef_construction in pgvector) improve the graph itself at the cost of a slower build and a larger index; change them only if raising the query setting stops helping.

To measure recall you need exact answers. In pgvector, run the same query without the index (for example with index scans disabled in a session); in MongoDB, set exact: true on $vectorSearch.

Filtering without losing results

Filtering is where the two designs differ most. pgvector's index does not know about your WHERE clause: it returns its nearest candidates and PostgreSQL drops those that fail the filter. With a selective filter, few candidates survive, and a query asking for 10 rows can return fewer. pgvector 0.8 added iterative index scans: with hnsw.iterative_scan set, the scan keeps going until enough rows pass. In the benchmark, a filter matching 10% of rows with iterative scans returned all 10 results with recall 0.983.

MongoDB indexes filter fields inside the vector index and applies the filter during the search, so the candidate list is already restricted. With numCandidates = 200, the filtered query returned 10 results with recall 1.000 and about 1.5 ms more latency than the unfiltered one. For very selective filters on few known values, pgvector also supports partial indexes and partitioning, which keep each index small.

Indexing and write performance

For a one-off load, both took about 15 seconds to index 100,000 vectors. The ongoing behaviour differs. In PostgreSQL every insert updates the HNSW graph inside the transaction, so writes slow down as the index grows, but a committed row is immediately searchable. In MongoDB the write is fast and mongot catches up from the change stream; a just-written document may not appear in search for a short time. For RAG over documents that change a few times a day, neither matters. For "search what I just saved" features, PostgreSQL's transactional visibility is simpler to reason about.

Memory and storage

HNSW is fastest when the index fits in memory. Here the pgvector index for 100,000 384-dimension vectors took 195 MB, more than the 156 MB table. As a rough guide, index size grows with the number of vectors times the dimensions; at millions of vectors, plan memory for it explicitly. Both systems can shrink vectors: pgvector with halfvec (half precision) and binary quantization, MongoDB with scalar or binary quantization set in the index definition. Smaller vectors cut memory and often speed up search, at some loss of recall that you should measure with the same harness.

Scaling past one machine

PostgreSQL scales vector reads with read replicas and partitioning, and writes with a bigger primary; distributed extensions exist but add complexity. A single well-sized node handles millions of vectors for many applications. MongoDB scales with sharding, and on Atlas, search can run on dedicated search nodes sized separately from the database, so heavy vector traffic does not compete with ordinary queries. If vector search will be a large share of your load, that separation is MongoDB's strongest argument.

Cost and operations

The cheapest system is usually the one you already run. If your application data lives in PostgreSQL, pgvector adds an extension, not a service: the same backups, monitoring and access control cover your vectors. If it lives in MongoDB, Vector Search keeps vectors next to documents without another database. Running a second database just for vectors means syncing data between them, which is where bugs and stale results come from. Price your managed tiers on your own expected data size and query rate; this article does not quote prices, because they change and depend on region and tier.

Security considerations

  • Filter by tenant in the query, with a WHERE clause or row-level security in PostgreSQL, or an indexed filter field in MongoDB, so a search can never return another customer's data.
  • Use least-privilege database users for the search path: read on the vector table or collection, nothing else.
  • Treat embeddings as sensitive. Research has shown text can be partly reconstructed from embeddings, so protect them like the text they came from.
  • Validate query input size before embedding, and rate-limit search endpoints.

Common mistakes and how to fix them

MistakeSymptomFix
Leaving pgvector at ef_search = 40Recall around 0.92 in this testRaise to 100 or more and measure
numCandidates equal to limitPoor recall in MongoDBUse at least 20 times limit
Filtering in pgvector without iterative scansFewer than k results for selective filtersSET hnsw.iterative_scan = relaxed_order, or partial indexes
Filtering on a field not declared in the MongoDB indexThe query failsAdd it as a filter field in the index definition
Querying MongoDB before the index is queryableEmpty results right after creating the indexPoll listSearchIndexes for queryable
Building HNSW in a container with 64 MB of shared memorycould not resize shared memory segmentRaise --shm-size or lower maintenance_work_mem
Registering pgvector types before the extension existsvector type not found in the databaseCreate the extension with a plain client first
Comparing systems on different hardwareConclusions that do not holdSame data, same queries, same machine, measured recall

Limitations of this benchmark

This is one run on one laptop, with both databases in Docker sharing the same CPU and memory. The data is synthetic, the queries are sequential from a single client, and 100,000 vectors is small. It does not measure concurrency, behaviour under writes, millions of vectors, Atlas cloud tiers or dedicated search nodes, and the MongoDB numbers come from the local Atlas image, not a managed cluster. Treat the numbers as a demonstration of how each system responds to tuning, and run the harness on your own data before making a decision.

Which should you choose?

If you...ChooseWhy
Already run PostgreSQLpgvectorOne system, SQL joins, transactional visibility
Already run MongoDB or AtlasMongoDB Vector SearchVectors next to documents, no second database
Need heavy, selective filtersEither, set up correctlyIterative scans or partial indexes in pgvector; filter fields in MongoDB
Expect search to dominate the loadMongoDB on Atlas, or a dedicated Postgres replicaIsolate search from transactional queries
Need new rows searchable immediatelypgvectorThe index updates in the same transaction

How to run your own benchmark

  1. Export 50,000 to 500,000 of your real embeddings and a few hundred real queries.
  2. Replace the generator in the harness with them; keep the brute-force ground truth.
  3. Start both databases with the Docker commands above, sized like production as far as you can.
  4. Run each setting and note recall and p50/p95 latency.
  5. Add the filters your application actually uses, and a test with concurrent clients.
  6. Pick the lowest setting that meets your recall target, then load-test that.

Summary

On identical data and hardware, pgvector answered faster per query and MongoDB reached near-perfect recall at its recommended setting; both built their indexes in about the same time and both handled a 10% filter without losing results once set up correctly. The settings mattered more than the database: pgvector's default ef_search left recall at 0.921. Choose the database you already run, tune the query setting against measured recall, and test filters and concurrency on your own data. To build the application around it, see the RAG pipeline with Next.js and pgvector.

Frequently asked questions

Is pgvector faster than MongoDB Vector Search?

In this benchmark, yes per query: about 3 ms median against 6.6 to 7.3 ms on the same 100,000 vectors and laptop. MongoDB reached higher recall at its recommended setting. Results on your data and hardware can differ.

What is the equivalent of ef_search in MongoDB?

numCandidates in the $vectorSearch stage. Both set how many candidates the HNSW search keeps; higher values raise recall and add a little latency.

What numCandidates should I use?

MongoDB recommends at least 20 times the limit. With limit 10, numCandidates 200 gave recall 0.999 in this test.

What ef_search should I use in pgvector?

The default is 40. In this test it gave recall 0.921; 100 gave 0.987 and 200 gave 0.998 with almost no extra latency. Measure on your own queries.

Do both databases use HNSW?

Yes. pgvector offers HNSW and IVFFlat; MongoDB Vector Search uses HNSW for approximate search and also supports exact search with exact: true.

How do filters work in pgvector and MongoDB?

pgvector applies WHERE after the index scan; iterative scans in pgvector 0.8 keep scanning until enough rows pass. MongoDB pre-filters on fields declared as filter fields in the vector index.

Why does my pgvector index build fail in Docker?

Parallel HNSW builds use shared memory, and Docker gives a container 64 MB by default. Start it with a larger --shm-size or lower maintenance_work_mem.

Are new MongoDB documents searchable immediately?

Not at the same instant. The vector index lives in mongot and is kept in sync from the database, so a new document appears in search shortly after it is written.

How big is a pgvector HNSW index?

Here, 195 MB for 100,000 vectors of 384 dimensions, larger than the 156 MB table. Plan memory so the index fits in RAM.

Can I test MongoDB Vector Search without Atlas?

Yes. The mongodb/mongodb-atlas-local Docker image runs mongod and mongot with the $vectorSearch stage on your machine.

Should I use a dedicated vector database instead?

Usually not at first. Start with the database you already run and move only when measurements show it cannot keep up.

How do I measure recall for vector search?

Compute the exact top k for a set of queries by brute force or with exact search, then count how many of those each approximate answer returns.

Sources

Free apps from the author of this guide