在数据库之间复制MongoDb索引

Rin*_*nce 4 indexing mongodb

我正在尝试在两个环境之间复制mongo索引。检查了API,没有发现直接的方法。所以我开始编写一个脚本,该脚本连接到一个数据库,遍历集合,获取索引,对其进行突变(因为getIndexes()ensureIndex()具有不同的格式),连接到另一个数据库,擦除索引并将新索引复制到其中。

这一切感觉都有些过分,所以我认为我一定想念一些东西。

有什么建议/好的做法吗?除了制定索引创建策略。

干杯!

小智 5

请在要复制索引的数据库上运行它。

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 + ')')
 })});
Run Code Online (Sandbox Code Playgroud)