Skip to content

Commit a5f6fce

Browse files
authored
Merge pull request #6044 from Countly/mrmeghana-patch-4
Create delete_empty_collections.js
2 parents b6ca70b + 01d7d2a commit a5f6fce

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}
20+
else if (delOK) {
21+
console.log("Collection dropped: " + collection);
22+
}
23+
else {
24+
console.log("Failed to drop collection: " + collection);
25+
}
26+
});
27+
}
28+
}
29+
else {
30+
console.log("Collection not found: " + collection);
31+
}
32+
});
33+
console.log("Collection drop process completed.");
34+
}
35+
// Fetch empty collections from countly_drill
36+
let emptyCollections = [];
37+
drill.listCollections().toArray(function(err, collections) {
38+
if (err) {
39+
console.log("Error fetching collections:", err);
40+
}
41+
else {
42+
collections.forEach(function(collection) {
43+
drill.collection(collection.name).countDocuments({}, function(err, count) {
44+
if (!err && count === 0) {
45+
console.log("Empty Collection: " + collection.name);
46+
emptyCollections.push(collection.name);
47+
}
48+
});
49+
});
50+
// Once empty collections are identified, proceed with dropping
51+
setTimeout(() => {
52+
console.log("\nDropping empty collections from countly_drill...");
53+
dropCollections(drill, emptyCollections, DRY_RUN);
54+
db.close();
55+
drill.close();
56+
}, 5000); // Delay to ensure collections are logged before drop
57+
}
58+
});
59+
});

0 commit comments

Comments
 (0)