Skip to content
Related Articles

Related Articles

Improve Article

How to rebuild all the indexes of a collection using PyMongo?

  • Last Updated : 26 May, 2020

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:

  1. 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

  2. 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)
  3. 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
  4. Accessing the Collection: We now select the collection from the database using the following syntax:
    collection_name = mydatabase.name_of_collection
  5. Rebuilding Index:

    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.


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
mydatabase = client.GFG
# Accessing the collection named
# Student
mycollection = mydatabase.Student
# Now rebuilding all the indexes of
# the collection



 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :