s1n7ax
s1n7ax

Reputation: 3069

Pymodm - Mongodb, How to create an index in a collection

I'm trying to create server side flask session extension that expires after # time. I found below Mongodb shell command in the documentation.

db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

But how can I do it using pymodm?

Upvotes: 1

Views: 1406

Answers (2)

Evhz
Evhz

Reputation: 9248

Form the docs:

indexes: This is a list of IndexModel instances that describe the indexes that should be created for this model. Indexes are created when the class definition is evaluated.

IndexModel is explained in this page.
Then add the following Meta class to your MongoModel class:

class Meta:
  indexes = [
    IndexModel([('createdAt', pymongo.ASCENDING)], expireAfterSeconds=3600)
  ]

Upvotes: 0

Luci Furtun
Luci Furtun

Reputation: 179

Take a look to the model definition: http://pymodm.readthedocs.io/en/stable/api/index.html?highlight=indexes#defining-models. There is a meta attribute called "indexes", that one is responsible for creating indexes. Here is an example:

import pymodm
import pymongo


class SomeModel(pymodm.MongoModel):

    ...

    class Meta:
        indexes=[pymongo.IndexModel([('field_name', <direction>)])]

Upvotes: 2

Related Questions