Search code examples
mongodbkotlinspring-data-mongodbmongodb-indexes

MongoDB - Can I use @TextIndexed and @Indexed on a field at the same time?


Is it possible to have both index and text index on the same column in MongoDB?

I want to query Question collection by country code (i.e. "US") and unwind related data in Country collection by country code as id.

Example code for Spring Data MongoDB / Kotlin:

@Document
data class Question(
    @Id val id: String,

    @TextIndexed
    @Indexed(name = "question_country_code_index")
    val countryCode: String
)

Solution

  • It is possible to apply both annotation to the very same property. The IndexResolver will then create two indexes.

    {
        "v" : 2,
        "key" : {
            "_fts" : "text",
            "_ftsx" : 1
        },
        "name" : "Question_TextIndex",
        "ns" : "db.question",
        "weights" : {
            "textIndexedPropertyWithDefaultWeight" : 1
        },
        "language_override" : "language",
        "textIndexVersion" : 3
    },
    {
        "v" : 2,
        "key" : {
            "countryCode" : 1
        },
        "name" : "question_country_code_index",
        "ns" : "db.question",
        "collation" : {
            ...
        }
    }