ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

복합 인덱스

복합 인덱스에는 컬렉션의 문서 내에 있는 여러 필드에 대한 참조가 포함되어 있어 쿼리 및 정렬 성능을 향상시킵니다.

복합 인덱스 를 생성할 때는 다음을 지정해야 합니다.

  • 인덱스 를 생성할 필드

  • 각 필드 의 정렬 순서(오름차순 또는 내림차순)

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트sample_mflix 데이터베이스 에 있는 movies 컬렉션 을 사용합니다. 무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.

다음 코틀린 (Kotlin) 데이터 클래스는 이 컬렉션 의 문서를 모델링합니다.

data class Movie(
@BsonId
val id: ObjectId,
val title: String? = "",
val type: String? = "",
val genres: List<String>? = null,
val cast: List<String>? = null,
val plot: String? = "",
)

다음 예시 에서는 typegenre 필드에 복합 인덱스 를 생성하며, 두 필드 모두 오름차순으로 인덱싱됩니다.

collection.createIndex(Indexes.ascending(Movie::type.name, Movie::genres.name))

다음은 앞의 코드 샘플 에서 생성된 인덱스 를 사용하는 쿼리 의 예시 입니다.

val filter = and(
eq(Movie::type.name, "movie"),
`in`(Movie::genres.name, "Drama")
)
val sort = Sorts.ascending(Movie::type.name, Movie::genres.name)
val results = collection.find(filter).sort(sort)
results.forEach { result ->
println(result)
}
Movie(id=573a1392f29313caabcda755, title=China Seas, type=movie, genres=[Action, Drama, Adventure], ...)
Movie(id=573a1392f29313caabcd9ca6, title=Scarface, type=movie, genres=[Action, Crime, Drama], ... )
Movie(id=573a1392f29313caabcdb258, title=The Hurricane, type=movie, genres=[Action, Drama, Romance], ...)
Movie(id=573a1391f29313caabcd820b, title=Beau Geste, type=movie, genres=[Action, Adventure, Drama], ...)
...

복합 인덱스에 학습 보려면 MongoDB Server 매뉴얼의 복합 인덱스 를 참조하세요.

복합 인덱스를 사용한 효과적인 인덱싱 전략에 학습 보려면 MongoDB Server 매뉴얼 의 ESR 규칙 을 참조하세요.

이 가이드에서 설명하는 메서드에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.