我需要删除一个MongoDB集合,然后使用与以前相同的索引重新创建它。但是我不想对索引进行硬编码。我想自动检索索引,将它们存储在某个地方,然后删除并重新创建集合后将它们传递回去。该程序将通过cron作业在每晚运行。这就是我被困住的地方:
<MONGO Connector code...>
MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collectionX = mongoDatabase.getCollection("XCollection");
ListIndexesIterable<Document> indexes = collectionX.listIndexes();
collectionX.drop();
mongoDatabase.createCollection("XCollection");
collectionX.createIndex(indexes); //Throws exception "createIndex (org.bson.conversions.Bson) in MongoCollection cannot be applied to (com.mongodb.client.ListIndexesIterable<org.bson.Document>)"
-----------------------------------------------------------
Another way...
for (Document document : indexes) {
collectionX.createIndex(document);
}
This throws error too: Exception in thread "main" com.mongodb.MongoCommandException: Command failed with error 67: 'Unknown index plugin '_id_'' on server XX.XXX.XXX.XX:XXXXX. The full response is { "ok" : 0.0, "errmsg" : "Unknown index plugin '_id_'", "code" : 67, "codeName" : "CannotCreateIndex" }