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