# MongoDB 与 PostgreSQL 向量搜索性能优化对比

URL: https://byshahid.com/zh/engineering/mongodb-atlas-vector-search-vs-pgvector/
Author: Muhammad Shahid, Senior AI Software Engineer & Full Stack Developer (https://byshahid.com/)
Published: 2026-11-12

**快速解答:** 在同样的 10 万个向量和同一台电脑上，pgvector 在 ef_search = 100 时中位延迟约 3 毫秒、recall@10 为 0.987；MongoDB 向量搜索在 numCandidates = 200 时中位延迟约 6.6 毫秒、召回率 0.999。两者都使用 HNSW，建索引都约 15 秒。本次测试中 pgvector 单次查询更快，MongoDB 在官方推荐设置下召回率接近满分。调好 ef_search 和 numCandidates 比选哪个数据库更重要。

- **数据:** 10 万个向量，384 维，余弦相似度，200 次查询，k = 10
- **PostgreSQL:** PostgreSQL 17 + pgvector 0.8.7，HNSW m = 16、ef_construction = 64
- **MongoDB:** Atlas Local 9.0.4（$vectorSearch、mongot），过滤字段已建索引
- **机器:** Apple M1 Pro、Docker、单客户端、顺序查询
- **代码:** TypeScript、mongodb 7.8 驱动、pg 8 + pgvector；所有数字来自同一次运行

大多数关于 **MongoDB Atlas 向量搜索与 PostgreSQL pgvector 性能**的对比，引用的都是厂商在不同硬件上的数据。本文把两者放在同一台机器上，用同样的 10 万个向量和同样的 200 个问题，在多种设置下测量召回率和延迟，并给出全部代码，方便你在自己的数据上复现。下面的数字来自在 Apple M1 Pro 上的一次运行，两个数据库都跑在 Docker 中。它们展示了两者的行为和调优方式，并不代表你的生产集群会得到同样的结果。

## 向量搜索谁更快：MongoDB 还是 PostgreSQL？

在本次测试中，**pgvector 的单次查询更快**：中位数约 3 毫秒，而 MongoDB 为 6.6 到 7.3 毫秒。**MongoDB 在其推荐设置下召回率更高**：`numCandidates = 200` 时为 0.999，而 pgvector 需要 `ef_search = 200` 才达到 0.998。两边建索引都约 15 秒。客观地说，在这个规模下两者对大多数应用都足够快，更大的差异在架构上：索引放在哪里、过滤如何工作、写入后多久能被搜到。

## 两个数据库中的向量搜索是怎么工作的

![向量索引的位置：在 PostgreSQL 中，HNSW 索引和表在同一个进程里；在 MongoDB 中，HNSW 索引位于 mongot，这是一个与 mongod 保持同步的独立搜索进程](https://byshahid.com/blog/img/engineering/mongodb-atlas-vector-search-vs-pgvector/architecture.svg)

*算法相同，在系统中的位置不同。*

两者都使用 **HNSW**（分层可导航小世界图），这种图索引无需把查询与每个向量逐一比较就能找到近邻。区别在于它运行在哪里。在 PostgreSQL 中，**pgvector** 把索引存放在表旁边、数据库进程之内，所以向量查询就是普通 SQL：可以联表、过滤、在事务中运行，新行在事务提交的那一刻即可被搜索。

在 MongoDB 中，向量索引位于 **mongot**，也就是 Atlas Search 和向量搜索背后的搜索进程。`mongod` 存储文档；`mongot` 维护自己的索引并与之同步，负责响应 `$vectorSearch` 阶段。这种分离让 Atlas 可以把搜索放在专用搜索节点上，但也意味着文档写入后要稍等片刻才能被搜到，而不是同一时刻，并且每次查询都多一跳。

## 测了什么，怎么测的

|  | PostgreSQL + pgvector | MongoDB 向量搜索 |
| --- | --- | --- |
| 版本 | PostgreSQL 17、pgvector 0.8.7 | MongoDB Atlas Local 9.0.4（mongod + mongot） |
| 索引 | HNSW，`vector_cosine_ops`，m = 16，ef_construction = 64 | vectorSearch 索引，余弦，`category` 作为过滤字段 |
| 测试的查询参数 | `ef_search` 40、100、200 | `numCandidates` 100、200、400 |
| 客户端 | 带 pgvector 类型的 node-postgres | MongoDB 官方 Node.js 驱动 7.8 |

数据是 10 万个合成的、已归一化的 384 维向量，分布在 200 个簇中，比均匀随机噪声更接近真实嵌入；另有一个取 10 个值的 `category` 字段。200 个查询来自同一分布，但不在数据集中。**Recall@10** 把每个结果与基准测试中暴力计算出的精确前 10 名进行比较。延迟是 Node.js 客户端发出单次查询的耗时，先做 20 次预热，再由一个客户端逐条发送查询。每次 pgvector 查询还会执行 `BEGIN`、一条 `SET LOCAL` 和 `COMMIT`，所以其延迟包含这些往返。

## 结果：召回率、延迟和构建时间

![recall@10 与中位延迟的散点图：pgvector 的点在 3 毫秒左右，召回率 0.921 到 0.998；MongoDB 的点在 6.6 到 7.3 毫秒，召回率 0.994 到 1.0](https://byshahid.com/blog/img/engineering/mongodb-atlas-vector-search-vs-pgvector/results.svg)

*每个点代表一种设置；越高、越靠左越好。*

| 设置 | Recall@10 | p50 延迟 | p95 延迟 |
| --- | --- | --- | --- |
| pgvector `ef_search = 40`（默认） | 0.921 | 3.0 ms | 6.0 ms |
| pgvector `ef_search = 100` | 0.987 | 2.9 ms | 5.9 ms |
| pgvector `ef_search = 200` | 0.998 | 3.4 ms | 8.0 ms |
| pgvector，按 category 过滤，`ef_search = 100`，迭代扫描 | 0.983 | 4.1 ms | 6.3 ms |
| MongoDB `numCandidates = 100` | 0.994 | 7.3 ms | 14.9 ms |
| MongoDB `numCandidates = 200` | 0.999 | 6.6 ms | 7.3 ms |
| MongoDB `numCandidates = 400` | 1.000 | 6.8 ms | 7.5 ms |
| MongoDB，按 category 过滤，`numCandidates = 200` | 1.000 | 8.1 ms | 9.4 ms |

| 加载与建索引 | PostgreSQL + pgvector | MongoDB |
| --- | --- | --- |
| 加载 10 万行或文档（每批 1,000） | 13.4 秒 | 5.4 秒 |
| 构建向量索引 | 14.8 秒 | 约 15 秒后可查询 |
| 磁盘占用 | 表 156 MB，HNSW 索引 195 MB | 未测量 |

## 这些数字说明了什么

- **`ef_search` 的默认值偏低。**在 pgvector 默认的 40 下，召回率为 0.921：每 12 个真正的近邻里差不多漏掉一个。调到 100 在这里几乎没有可测量的代价，召回率升到 0.987。在怀疑嵌入质量之前，先检查这个设置。

- **不同设置下延迟几乎持平。**在 10 万个向量上，扩大搜索范围在两个系统中增加的耗时都远小于 1 毫秒。在这个规模，查询的成本主要是固定开销（网络往返、查询规划、到搜索进程的额外一跳），而不是图遍历本身。

- **MongoDB 的建议是有效的。**MongoDB 建议 `numCandidates` 至少是 `limit` 的 20 倍。limit 为 10、取 200 时，召回率为 0.999。

- **两个系统中过滤都没有降低召回率**，前提是 pgvector 使用迭代扫描。下文详述。

- 在本次环境中，**向 MongoDB 加载数据更快**，而建索引用时差不多。

## 为高速搜索配置 pgvector

```bash
# 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
```

```bash
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
```

```ts
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();
  }
}
```

有三个细节很重要。第一，表结构用一个普通客户端创建，因为连接池会在每个新连接上注册 `vector` 类型，而在扩展创建之前这一步会失败。第二，HNSW 索引在批量加载*之后*再建，并给足 `maintenance_work_mem`；向已有的 HNSW 索引逐行插入要慢得多。第三，每次查询都放在一个短事务里，这样 `SET LOCAL` 只对这次查询修改 `hnsw.ef_search`，带过滤的查询还会修改 `hnsw.iterative_scan`。

基准测试中遇到了一个坑。pgvector 会用共享内存并行构建 HNSW 索引，而默认的 Docker 容器只有 64 MB 共享内存，于是构建失败：

```text
-- 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
```

用 `--shm-size=2g` 启动容器后问题解决。在普通服务器上很少遇到，但在容器和部分托管环境中，请把 `maintenance_work_mem` 控制在可用共享内存以下。

## 配置 MongoDB 向量搜索

```ts
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;
}
```

索引定义中列出向量字段及其维度和相似度，并把 `category` 声明为 `filter` 字段：只有这样声明的字段才能用于 `$vectorSearch` 的 `filter`。创建索引的调用会立即返回，索引在后台构建，所以代码会轮询 `listSearchIndexes`，直到 `queryable` 为 true；在此之前查询不会返回任何结果。查询用 `numCandidates` 指定候选列表大小、用 `limit` 指定结果数，并通过 `$meta: "vectorSearchScore"` 投影相似度。这里使用的本地 Atlas 镜像运行的 `$vectorSearch` 阶段与 Atlas 相同，无需云账号。

## 基准测试代码

```ts
// 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); });
```

```bash
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
```

这段代码为两个数据库生成同样的带种子数据，用暴力法计算精确答案，分别加载并建索引，然后对每种设置先做 20 次预热、再测量 200 次。你可以调整 `N`、维度或簇的离散程度来贴近你的数据；更好的做法是用你真实的嵌入和查询样本替换生成器，因为召回率在很大程度上取决于向量的分布。

## 调优召回率和速度

![调优参数对照表：pgvector 的 ef_search 对应 MongoDB 的 numCandidates；构建参数、过滤、精确搜索和量化并排比较](https://byshahid.com/blog/img/engineering/mongodb-atlas-vector-search-vs-pgvector/tuning.svg)

*同样的旋钮，不同的名字。*

`hnsw.ef_search` 和 `numCandidates` 作用相同：决定搜索遍历图时保留多少候选。值越大召回率越高，工作量也略多。像本基准测试一样，用带精确答案的真实查询样本来调，选出满足召回率目标的最小值。构建期参数（pgvector 的 `m` 和 `ef_construction`）会提升图本身的质量，代价是构建更慢、索引更大；只有在提高查询参数不再见效时才去调整它们。

测量召回率需要精确答案。在 pgvector 中，不走索引执行同一查询即可（例如在会话中关闭索引扫描）；在 MongoDB 中，在 `$vectorSearch` 里设置 `exact: true`。

## 过滤而不丢结果

过滤是两种设计差异最大的地方。pgvector 的索引并不知道你的 `WHERE` 条件：它返回最近的候选，再由 PostgreSQL 剔除不满足条件的行。过滤条件选择性很强时，留下的候选很少，要 10 行的查询可能返回不足 10 行。pgvector 0.8 新增了**迭代索引扫描**：设置 `hnsw.iterative_scan` 后，扫描会持续进行，直到有足够的行通过过滤。在基准测试中，命中 10% 行的过滤条件配合迭代扫描，返回了完整的 10 条结果，召回率 0.983。

MongoDB 会把过滤字段建进向量索引，在搜索过程中就应用过滤，因此候选列表本身已被限定。`numCandidates = 200` 时，带过滤的查询返回 10 条结果，召回率 1.000，比不带过滤的查询多约 1.5 毫秒。对于只取少数已知值、选择性极强的过滤，pgvector 还支持部分索引和分区，让每个索引保持小巧。

## 建索引与写入性能

一次性加载时，两者为 10 万个向量建索引都约 15 秒。持续写入时的表现不同。在 PostgreSQL 中，每次插入都在事务内更新 HNSW 图，索引越大写入越慢，但已提交的行立即可被搜索。在 MongoDB 中写入很快，`mongot` 再通过变更流追上进度；刚写入的文档可能有一小段时间搜不到。对于一天只变几次的文档做 RAG，这两点都无关紧要。对于“搜索我刚保存的内容”这类功能，PostgreSQL 的事务可见性更容易推理。

## 内存与存储

索引能完全放进内存时，HNSW 最快。这里 10 万个 384 维向量的 pgvector 索引占 195 MB，比 156 MB 的表还大。粗略地说，索引大小随向量数量乘以维度增长；到数百万向量时，要明确为它规划内存。两个系统都能压缩向量：pgvector 有 `halfvec`（半精度）和二值量化，MongoDB 可在索引定义中设置标量或二值量化。更小的向量能节省内存，往往还能加快搜索，但召回率会有一定损失，应该用同一套代码测量。

## 超出单机时如何扩展

PostgreSQL 通过只读副本和分区扩展向量读取，通过更强的主库承载写入；也有分布式扩展，但会增加复杂度。对很多应用来说，一个规格合适的单节点就能处理数百万个向量。MongoDB 通过分片扩展；在 Atlas 上，搜索可以运行在与数据库分开配置的专用搜索节点上，大量向量查询不会与普通查询争抢资源。如果向量搜索会占你负载的很大一部分，这种分离是 MongoDB 最有力的理由。

## 成本与运维

最便宜的系统通常是你已经在用的那个。如果应用数据在 PostgreSQL 里，pgvector 只是加一个扩展，而不是一个新服务：现有的备份、监控和权限控制同样覆盖向量。如果数据在 MongoDB 里，向量搜索让向量和文档放在一起，无需另一个数据库。单独为向量再跑一个数据库，就意味着要在两者之间同步数据，而 bug 和过期结果往往就出在这里。请按你预计的数据量和查询量评估托管方案的价格；本文不引用价格，因为价格会变，且取决于地区和规格。

## 安全注意事项

- **在查询中按租户过滤**：在 PostgreSQL 中用 `WHERE` 条件或行级安全，在 MongoDB 中用已建索引的过滤字段，确保搜索永远不会返回其他客户的数据。

- **为搜索路径使用最小权限的数据库用户**：只读向量表或集合，别无其他权限。

- **把嵌入视为敏感数据。**已有研究表明可以从嵌入中部分还原原文，所以要像保护原文一样保护它们。

- 在生成嵌入之前**校验查询输入的大小**，并对搜索接口限流。

## 常见错误及解决方法

| 错误 | 现象 | 解决方法 |
| --- | --- | --- |
| pgvector 保持 `ef_search = 40` | 本次测试中召回率约 0.92 | 调到 100 或更高并测量 |
| `numCandidates` 等于 `limit` | MongoDB 召回率很差 | 至少取 `limit` 的 20 倍 |
| pgvector 过滤时不用迭代扫描 | 选择性强的过滤返回不足 k 条 | `SET hnsw.iterative_scan = relaxed_order`，或使用部分索引 |
| 按 MongoDB 索引中未声明的字段过滤 | 查询失败 | 在索引定义中把它加为 `filter` 字段 |
| MongoDB 索引可查询之前就发起查询 | 刚建完索引时返回空结果 | 轮询 `listSearchIndexes` 的 `queryable` |
| 在只有 64 MB 共享内存的容器中构建 HNSW | could not resize shared memory segment | 调大 `--shm-size` 或调小 `maintenance_work_mem` |
| 在扩展创建前注册 pgvector 类型 | vector type not found in the database | 先用普通客户端创建扩展 |
| 在不同硬件上比较系统 | 得出站不住脚的结论 | 同样的数据、同样的查询、同一台机器，并测量召回率 |

## 本基准测试的局限

这是在一台笔记本上的一次运行，两个数据库都在 Docker 中，共享同样的 CPU 和内存。数据是合成的，查询由单个客户端顺序发出，10 万个向量也属于小规模。它没有测量并发、写入压力下的表现、数百万向量、Atlas 云端规格或专用搜索节点，MongoDB 的数字也来自本地 Atlas 镜像而非托管集群。请把这些数字看作两者对调优的反应示例，在做决定之前用你自己的数据运行这套代码。

## 该选哪一个？

| 如果你…… | 选择 | 原因 |
| --- | --- | --- |
| 已经在用 PostgreSQL | pgvector | 一个系统、SQL 联表、事务可见性 |
| 已经在用 MongoDB 或 Atlas | MongoDB 向量搜索 | 向量与文档放在一起，无需第二个数据库 |
| 需要大量强选择性过滤 | 两者皆可，前提是配置正确 | pgvector 用迭代扫描或部分索引；MongoDB 用过滤字段 |
| 预计搜索会成为主要负载 | Atlas 上的 MongoDB，或专用的 Postgres 副本 | 把搜索与事务型查询隔离 |
| 需要新行立即可被搜索 | pgvector | 索引在同一事务中更新 |

## 如何运行你自己的基准测试

- 导出 5 万到 50 万条真实嵌入，以及几百条真实查询。

- 用它们替换代码中的生成器，保留暴力计算的基准答案。

- 用上面的 Docker 命令启动两个数据库，规格尽量接近生产环境。

- 运行每种设置，记录召回率和 p50/p95 延迟。

- 加入应用实际使用的过滤条件，以及多客户端并发的测试。

- 选出满足召回率目标的最小设置，再对它做压力测试。

## 总结

在相同的数据和硬件上，pgvector 单次查询更快，MongoDB 在推荐设置下召回率接近满分；两者建索引用时相近，配置正确时都能在 10% 的过滤条件下不丢结果。设置比数据库本身更重要：pgvector 默认的 `ef_search` 让召回率只有 0.921。选择你已经在用的数据库，对照实测召回率调好查询参数，并在自己的数据上测试过滤和并发。想围绕它构建应用，请看 [用 Next.js 和 pgvector 构建 RAG 流水线](/zh/engineering/nextjs-rag-pipeline-pgvector/)。

## 常见问题

### pgvector 比 MongoDB 向量搜索快吗？

在本次基准测试中，按单次查询来看是的：在同样的 10 万个向量和同一台电脑上，中位数约 3 毫秒，对比 6.6 到 7.3 毫秒。MongoDB 在推荐设置下召回率更高。你的数据和硬件可能得出不同结果。

### MongoDB 中与 ef_search 对应的是什么？

$vectorSearch 阶段中的 numCandidates。两者都决定 HNSW 搜索保留多少候选；值越大召回率越高，延迟略有增加。

### numCandidates 应该设多少？

MongoDB 建议至少为 limit 的 20 倍。limit 为 10 时，本次测试中 numCandidates 取 200 得到 0.999 的召回率。

### pgvector 的 ef_search 应该设多少？

默认值是 40。本次测试中它的召回率为 0.921；设为 100 得到 0.987，设为 200 得到 0.998，延迟几乎不变。请用你自己的查询测量。

### 两个数据库都用 HNSW 吗？

是的。pgvector 提供 HNSW 和 IVFFlat；MongoDB 向量搜索用 HNSW 做近似搜索，也支持用 exact: true 做精确搜索。

### pgvector 和 MongoDB 的过滤是怎么工作的？

pgvector 在索引扫描之后应用 WHERE；pgvector 0.8 的迭代扫描会持续扫描直到有足够的行通过。MongoDB 对在向量索引中声明为过滤字段的字段进行预过滤。

### 为什么 pgvector 索引在 Docker 中构建失败？

并行构建 HNSW 会使用共享内存，而 Docker 默认只给容器 64 MB。用更大的 --shm-size 启动容器，或调小 maintenance_work_mem。

### MongoDB 新写入的文档能立即被搜到吗？

不是同一时刻。向量索引位于 mongot，并从数据库同步，所以新文档会在写入后不久出现在搜索结果中。

### pgvector 的 HNSW 索引有多大？

本次测试中，10 万个 384 维向量的索引为 195 MB，比 156 MB 的表还大。请规划好内存，让索引能放进 RAM。

### 不用 Atlas 能测试 MongoDB 向量搜索吗？

可以。mongodb/mongodb-atlas-local Docker 镜像会在本机运行 mongod 和 mongot，并支持 $vectorSearch 阶段。

### 应该改用专用向量数据库吗？

一开始通常不需要。先用你已经在运行的数据库，只有在测量表明它扛不住时再迁移。

### 如何测量向量搜索的召回率？

对一组查询用暴力法或精确搜索算出精确的前 k 个结果，再统计每次近似查询返回了其中多少个。

## 来源

- [pgvector on GitHub: HNSW options, iterative scans, filtering](https://github.com/pgvector/pgvector)
- [MongoDB Docs: $vectorSearch stage (numCandidates, exact)](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/)
- [MongoDB Docs: Vector Search index fields, filters and quantization](https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-type/)
- [MongoDB Docs: Local Atlas deployment with Docker](https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/)
- [Docker Hub: mongodb/mongodb-atlas-local](https://hub.docker.com/r/mongodb/mongodb-atlas-local)
- [PostgreSQL Docs: maintenance_work_mem and shared memory](https://www.postgresql.org/docs/current/runtime-config-resource.html)
- [MongoDB Node.js driver](https://www.mongodb.com/docs/drivers/node/current/)

查看相关服务: https://byshahid.com/zh/hire/ai-integration-engineer/
