项目中遇到迁移mongodb数据库的需求,迁移中集合数据迁移成功,但是索引没有迁移过来(除了默认索引),然后对索引做迁移工作,把对mongodb数据库索引的迁移步骤记录下来,以便以后可以用到。
步骤:
①在原mongodb中查询出所有要迁移集合的索引
②把①中索引添加到目标mongodb数据库中
步骤一:查看要迁移集合的索引
方法1:可以单个集合查看,然后使用索引创建方法在 目标mongodb数据库中 一个一个添加,此方法比较繁琐,不推荐。
方法2:查看原mongodb数据库中的所有索引,编写脚本打印出对应索引的添加语句,复制粘贴到 目标mongodb数据库中去执行即可(推荐)
下面介绍方法2的执行过程:
//导出索引的脚本 兼容了唯一索引,和超时配置
var collectionList = db.getCollectionNames();
for(var index in collectionList){
var collection = collectionList[index];
var cur = db.getCollection(collection).getIndexes();
if(cur.length == 1){
continue;
}
for(var index1 in cur){
var next = cur[index1];
if(next["key"]["_id"] == '1'){
continue;
}
print(
"try{ db.getCollection(\""+collection+"\").ensureIndex("+JSON.stringify(next.key)+",{background:1, unique:" + (next.unique || false) + "" + (next.expireAfterSeconds > 0 ? ", expireAfterSeconds :" + next.expireAfterSeconds : "") + " })}catch(e){print(e)}")}}
把上面的导出索引脚本放到 原mongodb数据库中去运行,运行结果如下:

复制上面的打印输出内容,粘贴到 目标mongodb数据库中去执行:

执行成功:
