Skip to content

Commit 1c44559

Browse files
authored
Create delete_empty_collections.js
Purpose: to fetch all empty collections and delete only drill_events prefix collections.
1 parent 2aa1e35 commit 1c44559

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Description: Deletes empty collections from database.By default it checks to delete from drill database. You can further tweak it to delete from countly database by changing drill to db in parameters passed
3+
* Server: countly
4+
* Path: $(countly dir)/bin/scripts/expire-data
5+
* Command: node delete_empty_collections.js
6+
*/
7+
var plugins = require("../../../plugins/pluginManager");
8+
var Promise = require("bluebird");
9+
var DRY_RUN = true; // Set this to false to perform actual drop
10+
Promise.all([plugins.dbConnection("countly"), plugins.dbConnection("countly_drill")]).spread(function(db, drill) {
11+
function dropCollections(database, collections, dryRun) {
12+
collections.forEach(function(collection) {
13+
if (database.collection(collection)) {
14+
console.log((dryRun ? "[DRY RUN] " : "") + "Dropping collection: " + collection);
15+
if (!dryRun) {
16+
database.collection(collection).drop(function(err, delOK) {
17+
if (err) {
18+
console.log("Error dropping collection: " + collection, err);
19+
} else if (delOK) {
20+
console.log("Collection dropped: " + collection);
21+
} else {
22+
console.log("Failed to drop collection: " + collection);
23+
}
24+
});
25+
}
26+
} else {
27+
console.log("Collection not found: " + collection);
28+
}
29+
});
30+
console.log("Collection drop process completed.");
31+
}
32+
// Fetch empty collections from countly_drill
33+
let emptyCollections = [];
34+
drill.listCollections().toArray(function(err, collections) {
35+
if (err) {
36+
console.log("Error fetching collections:", err);
37+
} else {
38+
collections.forEach(function(collection) {
39+
drill.collection(collection.name).countDocuments({}, function(err, count) {
40+
if (!err && count === 0) {
41+
console.log("Empty Collection: " + collection.name);
42+
emptyCollections.push(collection.name);
43+
}
44+
});
45+
});
46+
// Once empty collections are identified, proceed with dropping
47+
setTimeout(() => {
48+
console.log("\nDropping empty collections from countly_drill...");
49+
dropCollections(drill, emptyCollections, DRY_RUN);
50+
db.close();
51+
drill.close();
52+
}, 5000); // Delay to ensure collections are logged before drop
53+
}
54+
});
55+
});

0 commit comments

Comments
 (0)