📜  Python MongoDB – drop_index 查询

📅  最后修改于: 2022-05-13 01:54:44.636000             🧑  作者: Mango

Python MongoDB – drop_index 查询

PyMongo 中的 drop_index() 库函数用于从数据库中的集合中删除索引,顾名思义。在本文中,我们将讨论如何使用带有 PyMongo 的Python应用程序从集合中删除索引。

什么是索引?

索引是 MongoDB 中用于提高查询执行效率的一种特殊数据结构。它们是在集合级别定义的,它们允许 MongoDB 限制它搜索的文档数量。 B-tree 数据结构用于 MongoDB 中的索引。索引有多种类型,例如单字段索引、复合索引、多键索引。为了便于理解,在本文中,我们将使用单字段索引。

在本地托管的 Mongo 服务器上,让我们创建一个包含学生集合的数据库测试。该数据库将保存有关学生的以下信息-

默认情况下,每个集合都有_id索引。所有集合都必须至少有一个索引。如果删除所有索引,则将自动生成一个新索引。我们可以通过运行以下命令查看存在的索引 -

现在,假设 mongo 服务器正在运行,我们可以运行以下代码来将名为 newIndex 的新索引添加到学生集合中:

示例 1:向集合添加索引

import pprint
import pymongo
  
# connection
try:
    client = pymongo.MongoClient()
    db = client['test']
    print('connection to the server established')
      
except Exception:
    print('Failed to Connect to server')
  
collection = db.students
  
  
# creating an index
resp = collection.create_index("newIndex")
  
# printing the auto generated name 
# returned by MongoDB
print(resp)
  
# index_information() is analogous 
# to getIndexes
pprint.pprint(collection.index_information())

输出:

我们可以看到自动生成的名称是 newIndex_1。

示例 2:从集合中删除索引

import pprint
import pymongo
  
  
try:
    client = pymongo.MongoClient()
    db = client['test']
    print('connection to the server established')
  
except Exception:
    print('Failed to Connect to server')
  
collection = db.students
  
# dropping the index using autogenerated
# name from MongoDB
collection.drop_index("newIndex_1")
  
# printing the indexes present on the collection
pprint.pprint(collection.index_information())

输出:

输出显示新插入的名为 newIndex 的索引已被删除,只保留了原始的 _id 索引。这是 drop_index() 的应用。