文档菜单
文档首页
/
MongoDB 手册
/ /

隐藏索引

本页内容

  • 行为
  • 限制
  • 示例

隐藏索引对查询规划器不可见,并且不能用于支持查询。查询规划器

通过从规划器中隐藏索引,您可以评估删除索引可能产生的潜在影响,而无需实际删除索引。如果影响是负面的,您可以选择取消隐藏索引,而不是重新创建已删除的索引。

除了在规划器中隐藏之外,隐藏的索引表现得像未隐藏的索引。例如

要创建一个 隐藏 索引,请使用 db.collection.createIndex() 方法,并将 hidden 选项设置为 true

注意

要使用 db.collection.createIndex() 中的 hidden 选项,您必须将 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

注意

要隐藏现有的索引,您可以使用 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 时才返回该字段。

由于隐藏的索引会完全维护,取消隐藏后索引立即可供使用。

返回

不区分大小写

本页内容