Pymodm Mongodb,如何在集合中创建索引

2024-04-19 02:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建服务器端flask会话扩展,该扩展将在#时间后过期。我在文档中找到了下面的Mongodbshell命令。在

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

但是我如何使用pymodm来完成呢?在


Tags: 文档命令logflaskdb服务器端时间events
2条回答

请看一下模型定义:http://pymodm.readthedocs.io/en/stable/api/index.html?highlight=indexes#defining-models。有一个名为“indexes”的元属性,负责创建索引。下面是一个例子:

import pymodm
import pymongo


class SomeModel(pymodm.MongoModel):

    ...

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

形成文件:

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.

索引模型在this页中进行了说明。
然后将以下元类添加到MongoModel类中:

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

相关问题 更多 >