Python MongoDB drop_index查询用法介绍

2021年3月12日13:02:18 发表评论 1,266 次浏览

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

语法:drop_index(index_or_name, session = None, ** kwargs)参数:index_or_name:通过在集合上调用create_index()或sure_index()方法生成的索引名称。如果通过name参数创建了自定义索引名称, 则应在此处传递自定义名称。 session:这是一个可选参数, 用于指定ClientSession(来自pymongo.client_session类)。 kwargs:这些是其他关键字参数(可选)。

什么是索引?

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

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

Python MongoDB – drop_index查询1

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

Python MongoDB – drop_index查询2

现在, 假设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())

输出如下:

Python MongoDB – drop_index查询3

我们可以看到, 自动生成的名称是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())

输出如下:

Python MongoDB – drop_index查询4

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

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: