MongoDB使用命令行导出导入索引
#重装了MongoDB,目前需要从生产环境导出索引到测试环境
导出json文件
./mongo mongodb://IP:Port/库名 --eval "printjson(db.集合名.getIndexes())" > 文件地址
./mongo mongodb://localhost:20000/db_zzyq --eval "printjson(db.pushTables.getIndexes())" > /opt/server/mongodb3.2.4/suoyin/indexes.json
新增js文件
新增一个js文件,将json文件中的数据作为indexes参数,collectionName参数为集合名。
const indexes =[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db_zzyq.dataTables"
},
{
"v" : 1,
"key" : {
"ifmId" : 1,
"sort_timestamp" : 1,
"articleType" : 1
},
"name" : "index_ifmId_sort_timestamp_articleType",
"ns" : "db_zzyq.dataTables",
"background" : true
}
];
const collectionName = "dataTables"
// 批量创建索引
indexes.forEach(idx => {
if (idx.name === "_id_") return;
const key = idx.key;
if (!key){
print(`跳过无效索引(无 key)`);
return;
}
const indexOptions = {};
for (var prop in idx) {
if (idx.hasOwnProperty(prop) && prop !== "key") {
indexOptions[prop] = idx[prop];
}
}
try {
db.getCollection(collectionName).createIndex(key, indexOptions);
print(`成功创建索引:${collectionName}.${idx.name}`);
} catch (e) {
print(`创建索引失败 ${collectionName}.${idx.name}:${e.message}`);
}
});
导入js文件
./mongo mongodb://IP:Port/库名 js文件
./mongo mongodb://localhost:20000/db_zzyq imp.js
结果

