mongodb 设置过期自动删除记录

refs:

https://docs.mongodb.com/manual/tutorial/expire-data/

 

mongodb所占空间越来越大,删除一些旧数据比较合理。发现有ttl功能,原本怀疑会有性能上的影响。

 

db.getCollection('DevLogCollection').createIndex( { "DateTime": 1 }, { expireAfterSeconds: 90*24*3600} )

实际发现还行,后面再待观察,DateTime为其中的过期字段,日志发生的时间。

 

查看原db中的index

db.getCollection('DevLogCollection').getIndexes()
/* 1 */
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "DevLogDb.DevLogCollection"
    },
    {
        "v" : 2,
        "key" : {
            "DateTime" : -1.0
        },
        "name" : "DateTime_-1",
        "ns" : "DevLogDb.DevLogCollection"
    },
    {
        "v" : 2,
        "key" : {
            "DeviceId" : 1.0,
            "DateTime" : -1.0
        },
        "name" : "DeviceId_1_DateTime_-1",
        "ns" : "DevLogDb.DevLogCollection"
    },
    {
        "v" : 2,
        "key" : {
            "DeviceId" : 1.0
        },
        "name" : "DeviceId_1",
        "ns" : "DevLogDb.DevLogCollection"
    }
]

放弃原有index


db.DevLogCollection.dropIndex({"DateTime":-1})


修改过期时间
db.runCommand({collMod: 'DevLogCollection',index: { keyPattern: { "DateTime": -1 },expireAfterSeconds: 90*24*3600}})

 

你可能感兴趣的:(db,mongodb)