MongoDB 定期清理历史数据


mongo 可以通过 shell 方式执行 javascript,所以可以借助 crontab 定时执行脚本的方式处理。

js 脚本内容:

const mongo_time_text = 'T00:00:00.000Z' // ISODate 时间类型格式需要
let time_limit = 14

function lastDay() {
    let currentDay = new Date()
    currentDay.setDate(currentDay.getDate() - time_limit)
    let year = currentDay.getFullYear()
    let month = currentDay.getMonth()+1
    let day = currentDay.getDate()
    return [year, month, day].join('-') + mongo_time_text
}

function start() {
    let date = lastDay()
    let ds = db.getMongo().getDB('ceshi')
    ds.imMessages.remove({"createTime": {"$lt": ISODate(date)}}) // 删除
    // ds.imMessages.find({"createTime": {"$lt": ISODate(date)}})
    // 检查 查找的内容是否正确
    // let cursor = ds.imMessages.find({"createTime": {"$lt": ISODate(date)}})
    // while (cursor.hasNext()) {
    //     printjson(cursor.next())
    //}
}

shell 执行命令

mongo --eval "load('/tmp/mongo/mongo-test.js'); start()" > /tmp/test_mongo.log


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM