How to use Python to Check if an Index Exists for a MongoDB Collection

Introduction

Indexing document fields in a MongoDB collection helps to facilitate search queries, making the searches run more efficiently. This tutorial will show how to determine if a MongoDB index exists with the Python driver. This tutorial will also touch on how to manage a MongoDB collection’s indexes in the Compass GUI.

Prerequisites

  • A good working knowledge of Python and its syntax.

  • The Python interpreter must be properly installed as the examples in this article have been tested in Python 3.

  • The low-level Python driver for MongoDB must be installed on the same machine. Execute the following command using the PIP package manager:

pip3 install pymongo

Enter the Mongo Shell by entering mongo in a terminal window to confirm the Python driver installed correctly.

  • A collection and database containing indexes on the MongoDB server to facilitate making API calls.

How to Check the MongoDB Version for Changes to the Collection Class API

Some attributes of the collection and database classes have changed or been depreciated. Execute the below commands to obtain the current version of MongoDB and the PyMongo driver before making the API calls explained in this tutorial.

Execute the following command to obtain the current version of MongoDB:

mongo --version

Using Python’s IDLE environment, or a Python interpreter in a terminal, run the following commands to verify the version of PyMongo:

import pymongo
pymongo.version

As of June 2019, MongoDB 4.0 is the latest stable release and works well with PyMongo v3.4 that installs using PIP.

The ensureIndex() Python method is deprecated in version 3.0 of MongoDB

The ensure_index() method has been deprecated. Unless an older release of Python, MongoDB (2.x or older) and its PyMongo driver are being used, other method calls to the Collection class must be employed. The method is now just an alias for the create_index() method.

How to Instantiate a MongoDB Collection Object in a Python Script

Create a new Python script in the project directory using the .py file extension with the touch command in a terminal window as shown here:

touch get_indexes.py

How to edit the Python script and import the pymongo library’s ‘MongoClient’ class

Execute the following script to use Python’s import keyword to import the MongoClient class from the Python driver’s library:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import the MongoClient class from the library
from pymongo import MongoClient

How to declare a new client instance of the Python driver for MongoDB

The default domain and port URL string for the MongoClient() method call is localhost:27017, however, a URL custom string to the method call can be passed with the following command:

# create an instance of the MongoDB client for Python
client = MongoClient('mongodb://localhost:27017')

How to instantiate a collection object from a client’s database

Execute the following command to create a collection instance from the client object, confirming the collection contains some documents and indexes:

# SomeDatabase.Some Collection
db = client["SomeDatabase"]
col = db["Some Collection"]

How to Obtain All of the Index Attributes for the MongoDB Collection Class

Mongo is constantly changing and updating the attributes of the Collection class. In order to know what method calls will work for a given version of MongoDB, iterate over all of the class’s attributes and print any attributes containing "index" in the method name using the following script:

# iterate the MongoDB collection object's attributes
for num, item in enumerate(dir(col)):
# look for all of the methods with "index"
if "index" in item:
# print the collection object's methods and attributes
print (item)

As shown in the following image, all of the attributes names containing "index" should print out:

How to Use the MongoDB Collection Object’s list_indexes() Method

The system.indexes.find() method is now deprecated in MongoDB versions 3.x and newer. The list_indexes() method, shown below, must be used instead:

# use the collection object's list_indexes() method to return a cursor
index_cursor = col.list_indexes()

# list_indexes() returns a CommandCursor object
print ("\nindex_cursor TYPE:", type(index_cursor))

How to iterate the CommandCursor object returned by list_indexes()

The collection’s built-in list_indexes() method will return a cursor (pymongo.command_cursor.CommandCursor) object. The cursor object should contain bson.son.SON class objects containing the index information. Execute the following script to iterate over the objects using the for keyword exactly the same as for any other MongoDB cursor object in Python:

# iterate the pymongo.command_cursor.CommandCursor object
for index in index_cursor:
# print the bson.son.SON object for each iteration
print ("\n")
print (index, "--", type(index))
print ("index.keys():", index.keys())
print ("NAME:", index["name"]) # index name
print ("VERSION:", index["v"]) # index version

# iterate the index bson object's key-value pairs
# using the object's items() method
for key, val in index.items():
print (key, "--->", val, "-- type:", type(val))

NOTE: Each iteration of the CommandCursor object has attributes like a typical Python dict object with key-value pairs. Every index must have a name and v (version) key associated with it.

How to use the Collection Object’s index_information() Method

A newer method library uses the index_information() API that returns an actual Python dict object of all the collection’s indexes. Here is an example:

# use the index_information() to list indexes
indexes = col.index_information()
print ("\nindex_information() TYPE:", type(indexes))

Iterate the dict response’s key-value pairs, making sure to use iter_items() for Python 2.7, by executing the following script:

# iterate the dict object returned by the method call
for key, val in indexes.items():
print (key, "--", val)

How to manage a MongoDB collection’s indexes in the Compass GUI

If the MongoDB Compass application is installed on the machine, the collection’s indexes can be viewed and managed by navigating to the collection name, on the left-hand side of the window, and then clicking on the “Indexes” tab:

Conclusion

This tutorial explained how to determine if a MongoDB index exists with the Python driver. The tutorial covered how to obtain a MongoDB collection’s index names and information using the official Python driver for MongoDB. The article also explained how to obtain index attributes for the MongoDB collection class, how to check for changes to the Collection class API, how to edit the Python script and import the PyMongo library, how to declare a new client instance, instantiate a collection object from a client’s database and how to manage indexes in the Compass GUI. Remember that some attributes of the collection and database classes have depreciated. This makes it necessary to obtain the current version of MongoDB and the PyMongo driver before making the API calls explained in this tutorial.

Just the Code

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import the MongoClient class from the library
from pymongo import MongoClient

# create an instance of the MongoDB client for Python
# this example explicitly passes host parameters
client = MongoClient('mongodb://localhost:27017')

# declare instances of the MongoDB database and collection
# SomeDatabase.Some Collection
db = client["SomeDatabase"]
col = db["Some Collection"]

# iterate the MongoDB collection object's attributes
for num, item in enumerate(dir(col)):
# look for all of the methods with "index"
if "index" in item:
# print the collection object's methods and attributes
print (item)

# DEPRECATED: system.indexes class's find() method
indexes = col.system.indexes.find({'name':'test', 'ns':'SomeDatabase.Coll'})
print ("\nindexes:", indexes)
print ("indexes.system.find():", type(indexes))

# DEPRECATED: iterate the Cursor object
for index in indexes:
print ("\nindex TYPE:", type(index))
print ("index:", index, "--", dir(index))

# use the collection object's list_indexes() method to return a cursor
index_cursor = col.list_indexes()

# list_indexes() returns a CommandCursor object
print ("\nindex_cursor TYPE:", type(index_cursor))

# iterate the pymongo.command_cursor.CommandCursor object
for index in index_cursor:
# print the bson.son.SON object for each iteration
print ("\n")
print (index, "--", type(index))
print ("index.keys():", index.keys())
print ("NAME:", index["name"]) # index name
print ("VERSION:", index["v"]) # index version

# iterate the index bson object's key-value pairs
# using the object's items() method
for key, val in index.items():
print (key, "--->", val, "-- type:", type(val))

# use the index_information() to list indexes
indexes = col.index_information()
print ("\nindex_information() TYPE:", type(indexes))

# iterate the dict object returned by the method call
for key, val in indexes.items():
print (key, "--", val)

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.