Skip to content

Instantly share code, notes, and snippets.

@alexbevi
Created March 23, 2020 15:22
Show Gist options
  • Save alexbevi/a10c04cd639a6bf2b234cb02c683b3f0 to your computer and use it in GitHub Desktop.
Save alexbevi/a10c04cd639a6bf2b234cb02c683b3f0 to your computer and use it in GitHub Desktop.
Return a summarized list of all collection and index uris for a MongoDB cluster
/**
* getBackingFilenames(filter)
*
* Function to return a summarized list of all collections and indexes within all databases.
* Passing *filter* will optionally filter the results by either the collection uri or
* the uri of any of the indexes within a collection.
*
* @samples
* // unfiltered
* printjson(getBackingFilenames());
*
* // filtered
* printjson(getBackingFilenames("index-69"));
* [
* {
* "database" : "test",
* "collection" : "c_cards",
* "uri" : "statistics:table:collection-68-4608413808805359221",
* "indexes" : [
* {
* "name" : "_id_",
* "uri" : "statistics:table:index-69-4608413808805359221"
* }
* ]
* },
* {
* "database" : "test",
* "collection" : "routings",
* "uri" : "statistics:table:collection-68--2700007046186051335",
* "indexes" : [
* {
* "name" : "_id_",
* "uri" : "statistics:table:index-69--2700007046186051335"
* }
* ]
* }
* ]
*
* @created 2020-03-23
* @author Alex Bevilacqua <[email protected]>
* */
function getBackingFilenames(filter) {
var results = [];
// iterate over each database and collection
db.getMongo().getDBNames().forEach(function(dbname) {
db.getSiblingDB(dbname).getCollectionNames().forEach(function(c) {
var coll = db.getSiblingDB(dbname).getCollection(c);
// extract collection stats with index stats
var s = coll.stats({ indexDetails: true });
var result = { database: dbname, collection: c, uri: s.wiredTiger.uri, indexes: [] };
var keys = Object.keys(s.indexDetails);
for (var i = 0; i < keys.length; i++) {
var idxUri = s.indexDetails[keys[i]].uri
// if a filter was defined see if it matches any index backing files
if (!filter || (filter && idxUri.includes(filter))) {
result.indexes.push({ name: keys[i], uri: idxUri });
}
}
// if a filter was provided check if we have any indexes that matched, and if not see if the collection
// uri matches
if (!filter || result.indexes.length > 0 || result.uri.includes(filter)) {
results.push(result);
}
});
});
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment