在Java上将mongo集合索引复制到另一个集合的最佳方法是什么



我正试图将一个mongo集合的索引复制到另一个数据库中的另一个集合。Java上最好的解决方案是什么?

我使用MongoTemplate来执行mongo操作。这就是我从原始(源(集合中获取索引的方法:

MongoCollection<Document> srcCollection = srcMongoTemplate.getCollection(collectionName);
ListIndexesIterable<Document> indexesList = srcCollection.listIndexes();

但是,我应该如何使用检索到的"indexesList"对象在另一个集合中创建相同的索引呢?

我想我必须使用类似的东西,但我不明白到底要向createIndexes方法传递什么参数。

ListIndexesIterable<Document> indexes = srcCollection.listIndexes();
dstCollection.createIndexes(???);

为了解决这个问题,我创建了一个开源库mongo-index-copy。它使用MongoDB Java Driver中的listIndexescreateIndexes方法将索引从一个集合复制到另一个集合。使用此库,您可以将所有索引从一个集合复制到另一个集合,也可以指定要复制的索引的名称。

mongo-index-copy首先从源集合中获取Document对象形式的索引定义。接下来,它将这些Document对象映射为有效的IndexModel对象(同时也映射了所有可能的IndexOptions(。最后,mongo-index-copy使用先前创建的IndexModel对象在目标集合上创建这些索引。

要使用它,您可以使用Maven/Gradle将mongo-index-copy导入到您的项目中,并调用适当的MongoIndexCopy方法,如下例所示:

public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
MongoCollection<?> sourceCollection = mongoDatabase.getCollection("sourceCollection");
MongoCollection<?> destinationCollection = mongoDatabase.getCollection("destinationCollection");
try {
List<String> copiedIndexes = MongoIndexCopy.copyAllIndexes(sourceCollection, destinationCollection);
System.out.println(copiedIndexes);
} catch (MongoIndexCopyException e) {
// Handle exception
}
}

最新更新