zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

如何将一个mongodb中集合的索引 添加到另一个mongodb中集合中

MongoDB索引集合 如何 一个 添加
2023-09-11 14:20:19 时间

一、前言

项目中遇到迁移mongodb数据库的需求,迁移中集合数据迁移成功,但是索引没有迁移过来(除了默认索引),然后对索引做迁移工作,把对mongodb数据库索引的迁移步骤记录下来,以便以后可以用到。

二、mongodb索引 迁移

步骤:
①在原mongodb中查询出所有要迁移集合的索引
②把①中索引添加到目标mongodb数据库中

步骤一:查看要迁移集合的索引
方法1:可以单个集合查看,然后使用索引创建方法在 目标mongodb数据库中 一个一个添加,此方法比较繁琐,不推荐。
方法2:查看原mongodb数据库中的所有索引,编写脚本打印出对应索引的添加语句,复制粘贴到 目标mongodb数据库中去执行即可(推荐

下面介绍方法2的执行过程:

1.编写脚本,导出索引执行记录

//导出索引的脚本 兼容了唯一索引,和超时配置
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数据库中去运行,运行结果如下:
在这里插入图片描述

2.复制导出索引执行记录,去目标mongodb数据库中执行

复制上面的打印输出内容,粘贴到 目标mongodb数据库中去执行:
在这里插入图片描述

执行成功:
在这里插入图片描述