Prerequisites: MongoDB Python Basics
This article is about rebuilding the indexes of the collection in MongoDB using PyMongo reindex() function.
According to MongoDB documentation:
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.
The collection indexes may take more than disproportionate amount of disk space, and this problem can be solved by rebuilding the index of the collection.
Let’s begin with rebuilding the index of Collection:
- Importing Required Modules: Import the required module using the command:
from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
- Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).
client = MongoClient(‘localhost’, 27017)
- Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.
mydatabase = client.name_of_the_database
- Accessing the Collection: We now select the collection from the database using the following syntax:
collection_name = mydatabase.name_of_collection
- Rebuilding Index:
collection_name.reindex()
The above statement rebuild all the indexes. Please use the above statement with caution as the rebuilding of indexes takes place in foreground that blocks all the operation on the MongoDB server.
Example:
Sample Database:
# 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() |
Output:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.