Skip to content
广告❤️成为赞助商

Automatic Index Creation

Use annotations to automatically create indexes, saving you from index maintenance and allowing you to focus on queries.

::: tip Database and Collection

  • To use the automatic index creation feature, the entity class must be annotated with @CollectionName, otherwise it will not be scanned.
  • All index annotations in this document can interact with @CollectionName, using the collection name and database properties configured by that annotation. :::

Configuration

  • To use MongoPlus's automatic index creation, you need to enable the feature.
  • For multi-module projects with different package names, specify the sub-packages containing index classes in the main configuration file:
yaml
mongo-plus:
    configuration:
        auto-create-index: true # Enable automatic index creation
        auto-scan-packages: # Specify sub-packages if module package names differ
          - com.xxxx.entity
          - com.xxxx.entity1

Annotations

@MongoIndex

  • Annotation-based automatic index creation
  • Creates indexes on specified MongoDB fields using this annotation
PropertyTypeRequiredDefaultDescription
nameStringNoField nameIndex name
uniquebooleanNofalseUnique index
directionIndexDirectionNoIndexDirection.ASCIndex sorting direction
sparsebooleanNofalseSparse index
expireAfterSecondslongNo-1Index expiration time in seconds
expireAfterStringNo""Expiration time in custom format
partialFilterExpressionStringNo""Partial index, e.g., {"$gt",5}
backgroundbooleanNofalseWhether to create index in the background

::: tip expireAfter examples:

  • Days: @MongoIndex(expireAfter = "1d")
  • Hours: @MongoIndex(expireAfter = "3h")
  • Minutes: @MongoIndex(expireAfter = "30m")
  • Seconds: @MongoIndex(expireAfter = "30s") :::

Example

java
@CollectionName("user")
public class User {
    // Unique index
    @MongoIndex(unique = true)
    private String userName;
}

@MongoTextIndex

  • Annotation-based automatic text index creation
  • Creates a text index on specified MongoDB fields
  • Note: text index limitations
PropertyTypeRequiredDefaultDescription
fieldsString[]YesIndex fields; multiple fields form a compound text index
nameStringNoField nameIndex name
languageTextLanguagesNoTextLanguages.ENGLISHText language, default English
textIndexVersionlongNo-1Usually use default version; override only if needed for compatibility

@MongoHashIndex

  • Annotation-based automatic hash index creation
  • Creates a hash index on specified MongoDB fields

Example

java
@CollectionName("user")
public class User {
    @MongoHashIndex
    private String userName;
}

@MongoCompoundIndex

  • Annotation-based automatic compound index creation
  • Creates a compound index on specified MongoDB fields
  • Should be placed on class or inside @MongoCompoundIndexes container
PropertyTypeRequiredDefaultDescription
valueStringYesCompound index definition in JSON format
nameStringNoField nameIndex name
uniquebooleanNofalseUnique compound index
sparsebooleanNofalseSparse compound index
partialFilterExpressionStringNo""Partial index
backgroundbooleanNofalseCreate index in background

::: tip value property format:

  • Example: @CompoundIndex("{'field1':1,'field2':-1}") (-1 for descending, 1 for ascending)
  • $ can reference a field name in the class: @CompoundIndex("{'$field1':1,'$field2':-1}") uses the @CollectionField value if annotated :::

::: tip partialFilterExpression:

  • Example: {"field1": {"$gt", 5}}
  • $ can reference fields: {"$field1": {"$gt", 5}} :::

Example

java
@CollectionName("user")
@MongoCompoundIndex(
    value = "{'userName':1,'$userAge':-1}",
    unique = true,
    partialFilterExpression = "{\"$userAge\":{\"$gt\",5}}"
)
public class User {

    public String userName;

    @CollectionField("user_age")
    private Integer userAge;

}

@MongoCompoundIndexes

  • Multiple compound indexes
  • Combine multiple @MongoCompoundIndex annotations
PropertyTypeRequiredDefaultDescription
valueMongoCompoundIndex[]YesMultiple compound indexes

Example

java
@CollectionName("user")
@MongoCompoundIndexes({
    @MongoCompoundIndex(value = "{'$userName':1,'userAge':1}"),
    @MongoCompoundIndex(value = "{'$userStatus':1,'userAddress':1}")
})
public class User {

    public String userName;

    @CollectionField("user_age")
    private Integer userAge;

    private String userAddress;

    private Integer userAge;

    @MongoHashIndex
    private Integer userStatus;

}

@MongoGeoIndex

  • Automatically create 2dsphere or 2d indexes
  • Specify which type to create
PropertyTypeRequiredDefaultDescription
typeGeoTypeYesIndex type

Example

java
@CollectionName("user")
public class User {
    // Create 2dsphere index
    @MongoGeoIndex(type = GeoType.SPHERE)
    private Geometry location;
}

@MongoIndexDs

  • Data source for automatic index creation
  • Marks which data source the index should be created on
  • Defaults to main data source; optional
PropertyTypeRequiredDefaultDescription
dataSourceStringNoData source name