Skip to content

Instantly share code, notes, and snippets.

@wpottier
Last active July 2, 2021 02:18
Show Gist options
  • Save wpottier/a27064d2fd29e48f5643 to your computer and use it in GitHub Desktop.
Save wpottier/a27064d2fd29e48f5643 to your computer and use it in GitHub Desktop.
MongoDB copy indexes
db.getCollectionNames().forEach(function(collection) {
indexes = db[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 + ')');
})});
@sivanomula
Copy link

sivanomula commented Mar 25, 2017

Hi,
Thanks for the script. I have tried using it, come across some issue that collation settings shows as [object ]. Please update..
db.Collection_Collation.ensureIndex({ "_id": 1},{name: "id",collation: [object BSON]})
db.Collection_Collation.ensureInde({ "_fts": "text", "_ftsx": 1},{name: "FullTextSearch",weights: [object BSON],default_language: "english",language_override: "language",textIndexVersion: 3})

@diegoavidal
Copy link

Thanks man!!!

@shrikanthdvg
Copy link

Hi,
This works fine, but my requirement is to get the indexes for all the existing databases from above script i have to manually type the database name and it is hard if there are multiple databases.
It would be great if i get indexes of all the databases along with use database; so that i copy the same on other server to create schema and indexes.
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment