Skip to content

Instantly share code, notes, and snippets.

@marcusdb
Last active February 11, 2016 16:12
Show Gist options
  • Select an option

  • Save marcusdb/b3025b7f5e9ff3b5678e to your computer and use it in GitHub Desktop.

Select an option

Save marcusdb/b3025b7f5e9ff3b5678e to your computer and use it in GitHub Desktop.
mongoIndexExport
db.getCollectionNames().forEach(function(collection) {
var indexes = db.getCollection(collection).getIndexes();
indexes.forEach(function(c) {
opt = ''
ixkey = JSON.stringify(c.key, null, 1).replace(/(\r\n|\n|\r)/gm, "")
ns = c.ns.substr(c.ns.indexOf(".") + 1, c.ns.length)
for (var key in c) {
if (key != 'key' && key != 'ns' && key != 'v') {
if (opt != '') {
opt += ','
}
if (c.hasOwnProperty(key)) {
if (typeof(c[key]) == "string") {
opt += (key + ': "' + c[key] + '"')
} else {
opt += (key + ": " + c[key])
}
}
}
}
if (opt != '') {
opt = '{' + opt + '}'
}
print('db.' + ns + '.ensureIndex(' + ixkey + ',' + opt + ')')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment