This snippet offers an approach for managing MongoDB indexes, it's not specific to MongoFrames and uses PyMongo to create and drop indexes.

Defining indexes

Indexes for each collection are defined against the associated Frame class using the _index attribute:

from mongoframes import *

class Dragon(Frame):

    _fields = {

    _indexes = [
        IndexModel([('name', ASC)], unique=True),
        IndexModel([('breed', ASC)])

Consider using background=True for large indexes that could take a while to rebuild. Rebuilding the index in the background allows read and write operations against the collection while an index is being built.

Update indexes

To create/drop the indexes for each collection we use a command line script that we can call as and when we need to rebuild our indexes:


import argparse

# Import Frame classes
from dragons import Dragon

# Build a table of Frame classes
frame_cls_table = {
    Dragon._collection: Dragon,

def rebuild_indexes(collection_names):
    """(Re)build database indexes"""

    # If the only collection specified is all then rebuild all indexes
    if len(collection_names) == 1 and collection_names[0] == 'all':
        collection_names = frame_cls_table.keys()

    for name in collection_names:

        # Find the class for the collection
        frame_cls = frame_cls_table.get(name)
        assert frame_cls, 'Class not defined for collection: ' + name

        # Drop all indexes for the collection then recreate them

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='(Re)build database indexes')
    parser.add_argument('collections', type=string, nargs='+')
    args = parser.parse_args()


Whenever we need to update indexes for a collection we adjust the _index attribute class against the class and call our script (where Dragon is the name of the collection to update indexes for):

$ python Dragon