隐藏索引对查询规划器不可见,也不能用于支持查询。
通过向规划器隐藏索引,您可以评估在不实际删除索引的情况下删除索引的潜在影响。如有不利影响,您可以取消隐藏该索引,而不必重新创建删除的索引。
行为
除了对规划器隐藏之外,隐藏索引的行为与未隐藏索引相同。例如:
如果隐藏索引是唯一索引,则该索引仍将其唯一约束应用于文档。
如果隐藏索引是 TTL 索引,该索引仍会使文档过期。
隐藏索引包含在
listIndexes和db.collection.getIndexes()结果中。隐藏索引在对集合执行写入操作时进行更新,并继续消耗磁盘空间和内存。因此,它们包含在各种统计操作中,例如
db.collection.stats()和$indexStats。隐藏未隐藏索引或取消隐藏索引都会重置其
$indexStats。隐藏已隐藏的索引或取消隐藏已取消隐藏的索引不会重置$indexStats。
限制
要隐藏索引,必须将 featureCompatibilityVersion 设置为
5.0或更大。您无法隐藏
_id索引。不能
cursor.hint()隐藏的索引。
示例
创建隐藏索引
要创建 hidden 索引,请使用 db.collection.createIndex() 方法,将 hidden 选项设置为 true。
注意
要将 hidden 选项与 db.collection.createIndex() 一起使用,您必须将 featureCompatibilityVersion 设置为 5.0 或更高。
例如,以下操作将在 borough 字段上创建隐藏的升序索引:
db.addresses.createIndex( { borough: 1 }, { hidden: true } );
要进行验证,请在 addresses 集合上运行 db.collection.getIndexes():
db.addresses.getIndexes()
操作会返回以下信息:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1 }, "name" : "borough_1", "hidden" : true } ]
仅当值为 true 时才返回索引选项 hidden(隐藏)。
隐藏现有索引
注意
要隐藏索引,必须将 featureCompatibilityVersion 设置为
5.0或更大。您无法隐藏
_id索引。
要隐藏现有索引,可以使用collMod命令或 mongosh辅助程序db.collection.hideIndex() 。
例如,创建一个不隐藏的索引:
db.restaurants.createIndex( { borough: 1, ratings: 1 } );
要隐藏索引,可以指定以下任一项:
将索引键规范文档指定为
db.collection.hideIndex()方法:db.restaurants.hideIndex( { borough: 1, ratings: 1 } ); // Specify the index key specification document db.collection.hideIndex()方法的索引名称:db.restaurants.hideIndex( "borough_1_ratings_1" ); // Specify the index name
要进行验证,请在 restaurants 集合上运行 db.collection.getIndexes():
db.restaurants.getIndexes()
操作会返回以下信息:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1, "ratings" : 1 }, "name" : "borough_1_ratings_1", "hidden" : true } ]
仅当值为 true 时才返回索引选项 hidden(隐藏)。
取消隐藏现有的索引
要取消对索引的隐藏状态,可以使用 collMod 命令或 mongosh 辅助方法 db.collection.unhideIndex()。您可以指定以下任一项:
将索引键规范文档指定为
db.collection.unhideIndex()方法:db.restaurants.unhideIndex( { borough: 1, city: 1 } ); // Specify the index key specification document db.collection.unhideIndex()方法的索引名称:db.restaurants.unhideIndex( "borough_1_ratings_1" ); // Specify the index name
要进行验证,请在 restaurants 集合上运行 db.collection.getIndexes():
db.restaurants.getIndexes()
操作会返回以下信息:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1, "ratings" : 1 }, "name" : "borough_1_ratings_1" } ]
索引选项 hidden 不再显示为 borough_1_ratings_1 索引的一部分,因为仅当值为 true 时才返回该字段。
由于索引在隐藏期间得到完全维护,因此一旦取消隐藏,索引就立即可用。