private static void removeDifferingIndexIfAny ( final MongoCollection collection , final Index index ) { val indexes = ( ListIndexesIterable < Document > ) collection . listIndexes ( ) ; var indexExistsWithDifferentOptions = false ; for ( val existingIndex : indexes ) { val keyMatches = existingIndex . get ( "key" ) . equals ( index . getIndexKeys ( ) ) ; val optionsMatch = index . getIndexOptions ( ) . entrySet ( ) . stream ( ) . allMatch ( entry -> entry . getValue ( ) . equals ( existingIndex . get ( entry . getKey ( ) ) ) ) ; val noExtraOptions = existingIndex . keySet ( ) . stream ( ) . allMatch ( key -> MONGO_INDEX_KEYS . contains ( key ) || index . getIndexOptions ( ) . keySet ( ) . contains ( key ) ) ; indexExistsWithDifferentOptions |= keyMatches && ! ( optionsMatch && noExtraOptions ) ; } if ( indexExistsWithDifferentOptions ) { LOGGER . debug ( "Removing MongoDb index [{}] from [{}] because it appears to already exist in a different form" , index . getIndexKeys ( ) , collection . getNamespace ( ) ) ; collection . dropIndex ( index . getIndexKeys ( ) ) ; } }
Remove any index with the same indexKey but differing indexOptions in anticipation of recreating it .