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}