Prerequisites: MongoDB Python Basics
This article is about displaying the information of Collection’s indexes using the index_information()
function of the PyMongo module.
index_information()
returns a dictionary where the keys are index names (as returned by create_index()
) and the values are dictionaries containing information about each index. The dictionary is guaranteed to contain at least a single key, “key” which is a list of (key, direction) pairs specifying the index (as passed to create_index()). It will also contain any other metadata about the indexes, except for the “ns” and “name” keys, which are cleaned.
Let’s begin:
- 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
- Getting the information of the indexes: Using the function index_information to get the information of all the indexes of the collection.
collection_name.index_information()
Example:
Sample Database:
# Python Program for demonstrating the # PyMongo Cursor to Pandas DataFrame # Importing required modules from pymongo import MongoClient from pandas import DataFrame # 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 # Displaying the information of all the indexes # using the function index_information() ind_info = mycollection.index_information() print (ind_info) |
Output:
{‘_id_’: {‘v’: 2, ‘key’: [(‘_id’, 1)], ‘ns’: ‘GFG.Student’}, ‘Roll No_1’: {‘v’: 2, ‘unique’: True, ‘key’: [(‘Roll No’, 1)], ‘ns’: ‘GFG.Student’}}
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.