Class MongoIndexUtils

java.lang.Object
io.agentscope.extensions.mongodb.MongoIndexUtils

public final class MongoIndexUtils extends Object
Utility for creating MongoDB indexes with automatic migration on IndexOptionsConflict (error code 85).

When an existing index has conflicting options (e.g. TTL value changed), this utility uses listIndexes() to find the actual index name by key pattern — not a guessed default name — so it works even when DBAs renamed the index.

  • Method Summary

    Modifier and Type
    Method
    Description
    static void
    createIndexWithMigration(com.mongodb.client.MongoCollection<org.bson.Document> collection, org.bson.conversions.Bson indexKeys, com.mongodb.client.model.IndexOptions options)
    Creates an index, migrating if an existing index has conflicting options (error 85).

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • createIndexWithMigration

      public static void createIndexWithMigration(com.mongodb.client.MongoCollection<org.bson.Document> collection, org.bson.conversions.Bson indexKeys, com.mongodb.client.model.IndexOptions options)
      Creates an index, migrating if an existing index has conflicting options (error 85).

      If createIndex fails with error 85, this method:

      1. Calls listIndexes() to find the existing index whose key pattern matches indexKeys.
      2. Drops that index by its actual name (not a guessed default), tolerating "index not found" if another node already dropped it.
      3. Re-creates the index with the new definition.

      The drop + recreate path is fault-tolerant for multi-node startup: if another node concurrently drops or recreates the same index, the operation degrades to a harmless no-op rather than failing the application bootstrap.

      Parameters:
      collection - the MongoDB collection
      indexKeys - the index key specification (e.g. Indexes.ascending("field"))
      options - the index options (e.g. TTL, sparse, unique)