如何使用 PyMongo 重建集合的所有索引?
先决条件: MongoDB Python基础
本文是关于使用 PyMongo reindex()函数在 MongoDB 中重建集合的索引。
根据 MongoDB 文档:
Normally, MongoDB compacts indexes during routine updates. For most users, the reIndex command is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space.
集合索引可能会占用超过不成比例的磁盘空间,这个问题可以通过重建集合的索引来解决。
让我们从重建 Collection 的索引开始:
- 导入所需模块:使用以下命令导入所需模块:
from pymongo import MongoClient
如果您的机器上尚未安装 MongoDB,您可以参考指南:使用Python安装 MongoDB 的指南
- 创建连接:现在我们已经导入了模块,是时候建立与 MongoDB 服务器的连接了,大概是在 localhost(主机名)的端口 27017(端口号)上运行。
client = MongoClient(‘localhost’, 27017)
- 访问数据库:因为与 MongoDB 服务器的连接已建立。我们现在可以创建或使用现有的数据库。
mydatabase = client.name_of_the_database
- 访问集合:我们现在使用以下语法从数据库中选择集合:
collection_name = mydatabase.name_of_collection
- 重建指数:
collection_name.reindex()
上述语句重建所有索引。请谨慎使用上述语句,因为索引的重建发生在前台,会阻塞 MongoDB 服务器上的所有操作。
例子:
样本数据库:
# Python Program for demonstrating the
# rebuilding of indexes in MongoDB
# Importing required modules
from pymongo import MongoClient
# Connecting to MongoDB server
# client = MongoClient('host_name',
# 'port_number')
client = MongoClient('localhost', 27017)
# Connecting to the database named
# GFG
mydatabase = client.GFG
# Accessing the collection named
# Student
mycollection = mydatabase.Student
# Now rebuilding all the indexes of
# the collection
mycollection.reindex()
输出: