Skip to content

Instantly share code, notes, and snippets.

@tonholis
Created July 3, 2019 15:04
Show Gist options
  • Save tonholis/67bed1e0d5d2f702891c0e8ed4cd8d3c to your computer and use it in GitHub Desktop.
Save tonholis/67bed1e0d5d2f702891c0e8ed4cd8d3c to your computer and use it in GitHub Desktop.
A NodeJS script to delete 'orphan' chunks in MongoDB/GridFS database
//How to run:
// node deleteGridFSChunks.js <hostname> <databaseName>
const { MongoClient } = require('mongodb');
const args = process.argv.slice(2);
async function main() {
if (args.length != 2)
{
console.info("Warning\nTwo arguments are required: Hostname and database name");
return;
}
const hostname = args[0];
const database = args[1];
const client = await MongoClient.connect(`mongodb://${hostname}:27017/`, { useNewUrlParser: true });
const db = client.db(database);
const serverStatus = await db.command({ "serverStatus": 1 });
console.log(`MongoDB server (${hostname}): ${serverStatus.version}`);
const chunks = db.collection('fs.chunks');
const cursor = await chunks.aggregate([
{
$group: { _id: "$files_id" }
},
{
$lookup: {
from: "fs.files",
localField: "_id",
foreignField: "_id",
as: "fileList"
}
},
{
$match: {
"fileList": { $size: 0 }
}
}
]);
let fileIds = await cursor.map(chunk => chunk._id).toArray();
let res = await chunks.deleteMany({ "files_id" : { "$in": fileIds } });
if (res.result.ok)
console.log("Deleted Count: " + res.deletedCount);
else
console.error("Unable to delete");
client.close();
}
main().catch(error => console.error(error.stack));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment