Create a mongodb collection index with expireAfterSeconds using pymongo

Viewed 182

I have a collection in mongodb. In my python program, I have a variable named coll point at it. I want to create an index on a specified field, digestedOn, which will cause expiration of the record after 7776000 seconds.

I know how to create a simple index in python: coll.create_index([( "digestedOn", pymongo.ASCENDING)]). Where do I stick the {"expireAfterSeconds": 7776000} part?

Here's my whole program, I need the last line fixed so that the index is created with expireAfterSeconds.

import pymongo
import ssl

def connect_to_mongo(host, port, ssls, user, password, auth_source):
    return pymongo.MongoClient(host, port, ssl=ssls, username=user, ssl_cert_reqs=ssl.CERT_NONE,
                               password=password, authSource=auth_source,
                               authMechanism='SCRAM-SHA-1', maxPoolSize=None)

client = connect_to_mongo(host="10.10.10.10", port=27017, ssls=True, user="user",
                          password="password",auth_source="admin")
db = client['logs']
colnames = db.list_collection_names()
coll = db[colnames[0]]
coll.create_index([( "digestedOn", pymongo.ASCENDING )])
1 Answers

Just pass it as a named parameter:

coll.create_index([( "digestedOn", pymongo.ASCENDING )], expireAfterSeconds=7776000)
Related