mongo获取库里的所有索引

本文介绍了如何使用MongoDB的JavaScriptAPI获取当前库下的集合名,并遍历每个集合,检查索引情况,根据需要创建或更新索引,包括处理collation和unique属性。特别提到新旧版本创建索引方式的变迁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL:

//获取当前库下的所有集合名称
var collectionList = db.getCollectionNames();
//遍历集合
for (var index in collectionList) {
    var collection = collectionList[index];
    //获取对应集合下的所有索引
    var cur = db.getCollection(collection).getIndexes();
    //不存在continue
    if (cur.length == 1) {
        continue;
    }
    //遍历所有索引
    for (var index1 in cur) {
        var next = cur[index1];
        //printjson(next);//用于打印获取的索引下 对应的属性
        if (next["key"]["_id"] == '1') {
            continue;
        }
       
         //可以加自身想要的属性逻辑 如:
         
         //判断是否有collection属性
        if (typeof(next.collation) != "undefined") {
        //拼接创建index的语句
            print("try{ db.getCollection(\"" + collection + "\").createIndex(" + JSON.stringify(next.key) + ",{background:1,name:" + JSON.stringify(next.name) + ",collation:{locale:" + JSON.stringify(next.collation.locale) + ",numericOrdering:" + next.collation.numericOrdering + " },unique:" + (next.unique || false) + " })}catch(e){print(e)}");
        } else {
            print(
                "try{ db.getCollection(\"" + collection + "\").createIndex(" + JSON.stringify(next.key) + ",{background:1,name:" + JSON.stringify(next.name) + " ,unique:" + (next.unique || false) + " })}catch(e){print(e)}"
            );
        }
    }
}


注:

1、Mongo两种建索引的方法:
createIndex():创建一个新的索引,存在会报错
ensureIndex():新版本已经弃用。在索引已经存在时会确保索引与要创建的索引一致

2、 Mongo提供两种建索引的方式:
foreground前台模式,它会阻塞用户对数据的读写操作直到index构建完毕;
background后台模式,不阻塞数据读写操作,独立的后台线程异步构建索引,此时仍然允许对数据的读写操作。
日常最好使用{background:true}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值