Created
July 17, 2021 14:36
-
-
Save arevindh/5e34213d1920222fdaf95c80d5fae96d to your computer and use it in GitHub Desktop.
mongo_prune_js.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// keep N-day worth of data | |
var days=7; | |
// change to false to have the script to really exclude old records | |
// from the database. While true, no change at all will be made to the DB | |
var dryrun=true; | |
var now = new Date().getTime(), | |
time_criteria = now ; | |
time_criteria_in_seconds = time_criteria / 1000; | |
print((dryrun ? "[dryrun] " : "") + "pruning data older than " + days + " days (" + time_criteria + ")... "); | |
use ace; | |
var collectionNames = db.getCollectionNames(); | |
for (i=0; i<collectionNames.length; i++) { | |
var name = collectionNames[i]; | |
var query = null; | |
if (name === 'event' || name === 'alarm') { | |
query = {time: {$lt:time_criteria}}; | |
} | |
if (query) { | |
count1 = db.getCollection(name).count(); | |
count2 = db.getCollection(name).find(query).count(); | |
print((dryrun ? "[dryrun] " : "") + "pruning " + count2 + " entries (total " + count1 + ") from " + name + "... "); | |
if (!dryrun) { | |
db.getCollection(name).remove(query); | |
db.runCommand({ compact: name }); | |
} | |
} | |
} | |
if (!dryrun) db.repairDatabase(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment