在 MongoDB 通配符索引中包含特定字段(wildcardProjection 实战)
介绍在 MongoDB 中创建通配符索引(Wildcard Index)时,如何使用 wildcardProjection 选项显式包含指定字段路径,并结合 explain() 验证索引命中效果。
在 MongoDB 中创建通配符索引(Wildcard Index)时,我们可以根据业务需要为整个文档或子文档建索引。如果集合中的字段非常多,全量通配符索引会占用过多存储与内存资源,此时可以使用 wildcardProjection 参数,显式指定仅对部分特定字段路径建立通配符索引。
本文通过具体示例演示如何在通配符索引中仅包含特定字段。
准备示例文档
假设我们有一个名为 pets 的集合,包含如下结构的文档:
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20,
"awards" : {
"Florida Dog Awards" : "Top Dog",
"New York Marathon" : "Fastest Dog",
"Sumo 2020" : "Biggest Dog"
}
}
}
{
"_id" : 2,
"name" : "Fetch",
"details" : {
"born" : ISODate("2020-06-22T14:00:00Z"),
"color" : "Black"
}
}
{
"_id" : 3,
"name" : "Scratch",
"details" : {
"eats" : [
"Mouse Porridge",
"Bird Soup",
"Caviar"
],
"type" : "Cat",
"born" : ISODate("2020-12-19T14:00:00Z")
}
}
创建带有 wildcardProjection 的通配符索引
我们希望建立通配符索引,但仅将 details.type 和 details.born 这两个子字段纳入索引范围。
可以在创建索引时传入 { "$**" : 1 } 作为键模式,并在第二个参数中配置 wildcardProjection 投影文档:
db.pets.createIndex(
{ "$**" : 1 },
{
"wildcardProjection" : {
"details.type" : 1,
"details.born" : 1
}
}
);
输出:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}在上面的语句中:
- 键规范
{ "$**" : 1 }表示创建通配符索引; wildcardProjection参数指定了具体的投影规则;- 将
"details.type" : 1与"details.born" : 1设为1,表示显式把这两个字段路径包含在索引树中。
[!NOTE] 在
wildcardProjection中,包含模式(1)与排除模式(0)通常不能混用,唯一的例外是对_id字段的显式排除(如_id: 0)。
查看索引元数据
使用 db.collection.getIndexes() 查看当前集合的索引状态:
db.pets.getIndexes();
输出:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"$**" : 1
},
"name" : "$**_1",
"wildcardProjection" : {
"details.type" : 1,
"details.born" : 1
}
}
]可以看到除了默认主键索引 _id_ 之外,新生成的通配符索引 $**_1 中包含了我们定义的 wildcardProjection 规则。
测试与验证查询执行计划
我们可以使用 explain() 检查 MongoDB 查询优化器是否命中了该索引。
命中索引的查询
对已包含在 wildcardProjection 中的 details.type 字段发起查询:
db.pets.find( { "details.type" : "Dog" } ).explain();
输出片段:
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "PetHotel.pets",
"indexFilterSet" : false,
"parsedQuery" : {
"details.type" : {
"$eq" : "Dog"
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"$_path" : 1,
"details.type" : 1
},
"indexName" : "$**_1",
"isMultiKey" : false
}
}
},
"ok" : 1
}执行计划显示 inputStage.stage 为 IXSCAN(索引扫描),使用的索引名称正是 $**_1。
未命中索引的查询
对未包含在 wildcardProjection 中的字段(例如 details.awards.New York Marathon)发起查询:
db.pets.find( { "details.awards.New York Marathon" : "Fastest Dog" } ).explain();
输出片段:
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "PetHotel.pets",
"indexFilterSet" : false,
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"details.awards.New York Marathon" : {
"$eq" : "Fastest Dog"
}
},
"direction" : "forward"
}
},
"ok" : 1
}执行计划显示为 COLLSCAN(全表/全集合扫描),证明不在 wildcardProjection 白名单中的字段不会被索引索引,符合预期。
总结
通配符索引是应对高度动态模式(Schemaless)文档的利器。通过合理配置 wildcardProjection,既能享受到通配符索引查询多态字段的灵活性,又能精准控制索引开销,避免不必要的存储膨胀与写放大。