云数据库 MongoDB 版模型服务,通过和 MongoDB Search 能力结合,无需额外部署向量数据库或推理服务,即可在 MongoDB 中完成向量检索和大模型调用。本文通过一个完整示例演示:写入纯文本 → 自动生成向量索引 → 用自然语言查询。
前提条件
已创建云数据库 MongoDB 8.3 或更高版本的副本集或分片集群实例。操作步骤参见创建实例。
本地已安装
mongosh(MongoDB Shell)。
开通 Search 节点
在实例详情页的左侧导航栏,选择 。
单击开启 Search 服务,选择 Search 节点的规格和数量后确认。
等待 Search 节点状态变为运行中(通常几分钟)。
开启后,实例支持 $search 和 $vectorSearch 聚合阶段,以及 createSearchIndexes 等 Search 索引管理命令。
开通模型服务
在实例详情页的左侧导航栏,选择。
单击立即开通,等待开通完成后,系统为实例分配一个独立的接入域名,并同时生成一个API Key。
dds-<实例ID>-aigateway.mongodbaiapp.<地域>.rds.aliyuncs.com
API Key 仅在创建时完整展示一次。如已泄露或丢失,请在控制台轮重新生成。
创建 Auto Embedding 向量索引
连接实例。连接信息可在控制台的数据库连接页面获取。
mongosh "mongodb://<用户名>:<密码>@dds-<实例ID>.mongodb.<地域>.rds.aliyuncs.com:3717,dds-<实例ID>.mongodb.<地域>.rds.aliyuncs.com:3717/admin?replicaSet=mgset-<副本集ID>"连接后执行以下脚本:
use("mydb");
// 1. 插入示例文档——只需纯文本,无需计算向量
db.articles.insertMany([
{ title: "Cat", content: "Cats are small, agile mammals often kept as pets" },
{ title: "Dog", content: "Dogs are loyal companions known for their trainability" },
{ title: "Bird", content: "Most birds can fly, and many migrate across continents" }
]);
// 2. 为 content 字段创建 autoEmbed 向量索引
// mongot 使用指定模型自动生成向量
db.runCommand({
createSearchIndexes: "articles",
indexes: [{
name: "vector_index",
type: "vectorSearch",
definition: {
fields: [
{ type: "autoEmbed", modality: "text", path: "content", model: "text-embedding-v4" },
{ type: "filter", path: "title" }
]
}
}]
});
// 3. 查看索引状态——queryable 为 true 时索引就绪
db.articles.aggregate([{ $listSearchIndexes: {} }]);数据量较小时,索引通常几秒内创建完成。输出中 queryable 为 true 即表示索引就绪。
执行语义检索
索引就绪后,使用自然语言查询。查询文本自动通过同一模型向量化。
db.articles.aggregate([
{
$vectorSearch: {
index: "vector_index",
path: "content",
query: "which animals can fly", // 纯文本,不是向量
numCandidates: 100,
limit: 3
}
},
{ $project: { title: 1, score: { $meta: "vectorSearchScore" } } }
]);预期结果:Bird 文档得分最高,因为其内容与查询"which animals can fly"语义最接近。
调用更多模型(可选)
MongoDB 模型服务还支持更多模型。可用模型包括:qwen3.6-flash、qwen3.6-plus、qwen3.5-flash、qwen3.5-plus、deepseek-v4-pro。
发送流式对话请求:
curl -X POST \
http://dds-<实例ID>-aigateway.mongodbaiapp.<地域>.rds.aliyuncs.com:8000/v1/chat \
-H "Authorization: Bearer <API Key>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
--no-buffer \
-d '{
"model": "qwen-plus",
"messages": [{"role": "user", "content": "你好"}],
"max_tokens": 100,
"stream": true
}'替换以下占位符:
占位符 | 获取位置 |
| 控制台实例详情页 |
| 实例部署的地域,如 |
| 模型服务 > API Key 管理 |
后续操作
混合检索:结合
$search(全文)和$vectorSearch(语义)提高召回质量。切换模型:修改
autoEmbed索引定义中的model字段即可更换 Embedding 模型,无需手动管理向量字段。