MongoDB如何将索引定义从一个集合复制到另一个集合?
我知道有一种方法可以执行db.collection.getIndexes(),该方法将列出为集合定义的所有索引.有没有办法将这些索引定义复制并创建到另一个集合?
I know there's a way to do db.collection.getIndexes() Which will list all the indexes defined for a collection. Is there a way to copy and create those index definitions to another collection?
有很多,我不想一个接一个地做.
There's a lot of them and I don't want to do them one by one.
关于重复的问题评论:我不希望复制收藏集.我希望以可以应用于其他集合的格式导出索引.
regarding the duplicated question comment: I do not wish to copy a collection. I wish to export indexes in a format that I can apply to another collection.
例如,我有一个现有的 user 集合,其索引为 _id _ , name_1 ,电子邮件_1 和网站_1
For example I have one existing user collection with indexes _id_, name_1, email_1 and website_1
然后我有另一个名为 usertest 的集合,我想将索引从 user 集合复制到 usertest 集合.以下命令适用于这种情况:
Then I have another collection called usertest, I want to copy indexes from user collection to usertest collection. The following commands works for this scenario:
-
同时复制索引键和索引选项
Copy both index key and index options
var indexes = db.user.getIndexes();
indexes.forEach(function(index){
delete index.v;
delete index.ns;
var key = index.key;
delete index.key
var options = [];
for (var option in index) {
options.push(index[option]);
}
db.usertest.createIndex(key, options);
});
仅复制索引键(批处理)
Copy index key only (batch processing)
var indexKeys = db.user.getIndexKeys();
db.usertest.createIndexes(indexKeys);
希望这会有所帮助.这是文档: createIndexes
Hope this will be helpful. Here's the doc: createIndexes