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