问题描述
如何把 mongoDB 中某个 collection 的 indexes 应用到另一个相似的 collection 上面?
首先可以通过这个原生的方法查看 index 列表
db.your_collection.getIndexes();
结果

但问题是这并不是可执行的语句,如何能像 mysql 一样导出创建 index 的语句,以便可以应用在新表上?
解决办法
根据我简单的 research 发现没有原生的方法可以实现,但是mongosh可以通过执行js script 来实现。
Step0: 新建/tmp/script.js 文件
var collectionList = db.getCollectionNames();
// var collectionList = ["foo","bar"]
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["name"] == "_id_") {
continue;
}
var unique = next["unique"] ? true : false;
print(
'db.getCollection("' +
collection +
'").createIndex(' +
JSON.stringify(next["key"]) +
",{unique:" +
unique +
"},{background:1});"
);
}
}
Step1: 通过mongosh执行 script
mongosh --quiet 'mongodb://$user:$passwd@$host:$port/$db?ssl=false&authSource=admin' /tmp/script.js > /tmp/result.txt
结果直接是可执行的 mongo 语句
db.getCollection("foo").createIndex({"created_time":1,"contract":1,"symbol":1},{unique:false},{background:1});
db.getCollection("foo").createIndex({"contract":1,"symbol":1},{unique:false},{background:1});
db.getCollection("foo").createIndex({"created_time":1},{unique:false},{background:1});
Step2: 根据自己的需求更新语句,然后应用在新 collection 上面







Helko colleagues, plleasant post andd pleasant arguments conmented att
thgis place, I am actrually enjoying byy these.
Very good info. Lucky mme I ran acroiss your bllg by accident (stumbleupon).
I have bookmatked itt for later!
Feeel freee tto surf to myy blpog pkst … pornadoo.com
Hi tere jst wanted tto give youu a qjick hheads up.
Thee woords in yohr poxt seem tto be running off thhe scree inn
Opera. I’m nott sure if thiss is a formattting issue orr somethibg tto doo witgh
webb browsr cimpatibility bbut I hought I’d post tto let yoou know.
Thee dessign aand style lokok grreat though! Hoppe yoou gget tthe
iissue reesolved soon. Thanks
Alsso visit mmy weeb page: txxxvideos.com
We arre a gaggle oof voluntders aand openning a brznd nnew schene
iin ouur community. Yoour site provided uss wiith usefuul infomation too
wolrk on. Youu hhave perfolrmed a formkdable job annd ourr whole neighborhood will probaby
bbe thankmful tto you.
my ssite :: txxxvideos.com
I every tiime spenmt mmy hqlf an hur too reazd this weeb site’s content everry daay along with a mmug off coffee.
Allso visi myy web blog; roloxxx.com (Maureen)