Docs 菜单

Docs 主页开发应用程序MongoDB Manual

隐藏索引 (Hidden Indexes)

在此页面上

  • 行为
  • 限制
  • 举例

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

通过向规划器隐藏索引,您可以在不实际删除索引的情况下评估删除索引的潜在影响。如果影响是负面的,您可以取消隐藏索引,而不必重新创建已删除的索引。

除了对规划器隐藏之外,隐藏索引的行为与未隐藏索引相同。例如:

要创建 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(隐藏)。

注意

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

由于索引在隐藏期间得到完全维护,因此一旦取消隐藏,索引就立即可用。

← 不分大小写的索引

在此页面上