문서 메뉴
문서 홈
/ / /
Kotlin 코루틴
/ / /

결과 정렬

이 페이지의 내용

  • 개요
  • 정렬 방법
  • 정렬 방향
  • 오름차순
  • 내림차순
  • 타이 처리
  • 정렬 기준 결합
  • 텍스트 검색

이 가이드에서는 정렬 작업을 사용하여 MongoDB 코틀린(Kotlin) 드라이버로 읽기 작업에서 결과의 순서를 지정하는 방법에 대해 설명합니다.

정렬 작업은 지정된 정렬 기준 에 따라 쿼리에서 반환된 문서를 정렬합니다. 정렬 기준은 데이터 정렬 방법을 설명하는 MongoDB에 전달하는 규칙입니다. 정렬 기준의 몇 가지 예는 다음과 같습니다.

  • 가장 작은 숫자에서 가장 큰 숫자로

  • 가장 이른 시간부터 가장 늦은 시간까지

  • 이름별 알파벳 순서

다음 조치를 수행하는 방법을 알아보려면 이 가이드를 읽어야 합니다.

  • 오름차순 정렬 및 내림차순 정렬 수행

  • 정렬 기준 결합

  • 텍스트의 텍스트 점수를 기준으로 정렬 Atlas Search

이 가이드의 예제에서는 다음 문서가 포함된 샘플 컬렉션을 사용합니다.

{ "_id": 1, "date": "2022-01-03", "orderTotal": 17.86, "description": "1/2 lb cream cheese and 1 dozen bagels" },
{ "_id": 2, "date": "2022-01-11", "orderTotal": 83.87, "description": "two medium vanilla birthday cakes" },
{ "_id": 3, "date": "2022-01-11", "orderTotal": 19.49, "description": "1 dozen vanilla cupcakes" },
{ "_id": 4, "date": "2022-01-15", "orderTotal": 43.62, "description": "2 chicken lunches and a diet coke" },
{ "_id": 5, "date": "2022-01-23", "orderTotal": 60.31, "description": "one large vanilla and chocolate cake" },
{ "_id": 6, "date": "2022-01-23", "orderTotal": 10.99, "description": "1 bagel, 1 orange juice, 1 muffin" }

이 데이터는 다음 Kotlin 데이터 클래스로 모델링됩니다.

data class Order(
@BsonId val id: Int,
val date: String,
val orderTotal: Double,
val description: String,
)

쿼리로 검색된 결과를 정렬하거나 집계 파이프라인 내에서 결과를 정렬할 수 있습니다.

쿼리 결과를 정렬하려면 FindFlow 인스턴스의 sort() 메서드를 사용합니다. 집계 파이프라인 내에서 결과를 정렬하려면 Aggregates.sort() 정적 팩토리 메서드를 사용합니다. 이 두 메서드 모두 Bson 인터페이스를 구현하는 객체를 인수로 받습니다. 자세한 내용은 BSON 인터페이스에 대한 API 설명서를 참조하세요.

다음과 같이 FindFlow 인스턴스의 sort() 메서드를 사용할 수 있습니다.

val resultsFlow = collection.find().sort(Sorts.ascending(Order::orderTotal.name))

집계 파이프라인 내에서 Aggregates.sort() 메서드를 사용하여 다음과 같이 샘플 컬렉션 의 문서를 orderTotal 필드의 가장 작은 값에서 가장 큰 값으로 정렬할 수 있습니다.

val resultsFlow = collection.aggregate(listOf(
Aggregates.sort(Sorts.ascending(Order::orderTotal.name))
))
resultsFlow.collect { println(it) }
Order(id=6, date=2022-01-23, orderTotal=10.99, description=1 bagel, 1 orange juice, 1 muffin)
Order(id=1, date=2022-01-03, orderTotal=17.86, description=1/2 lb cream cheese and 1 dozen bagels)
Order(id=3, date=2022-01-11, orderTotal=19.49, description=1 dozen vanilla cupcakes)
Order(id=4, date=2022-01-15, orderTotal=43.62, description=2 chicken lunches and a diet coke)
Order(id=5, date=2022-01-23, orderTotal=60.31, description=one large vanilla and chocolate cake)
Order(id=2, date=2022-01-11, orderTotal=83.87, description=two medium vanilla birthday cakes)

앞의 코드 스니펫에서는 Sorts 빌더 클래스를 사용하여 정렬 기준을 지정합니다. Bson 인터페이스를 구현하는 모든 클래스를 사용하여 정렬 기준을 지정할 수 있지만 Sorts 빌더를 통해 정렬 기준을 지정하는 것이 좋습니다. Sorts 빌더 클래스에 대한 자세한 내용은 정렬 빌더 가이드를 참조하세요.

이 섹션의 클래스 및 인터페이스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.

정렬 방향은 오름차순 또는 내림차순 중 하나일 수 있습니다. 오름차순 정렬은 결과가 가장 작은 순서에서 가장 큰 순서로 정렬됩니다. 내림차순 정렬은 결과가 가장 큰 순서에서 가장 작은 순서로 정렬됩니다.

다음은 오름차순으로 정렬된 데이터의 몇 가지 예입니다.

  • 숫자: 1, 2, 3, 43, 43, 55, 120

  • 날짜: 1990-03-10, 1995-01-01, 2005-10-30, 2005-12-21

  • 단어(ASCII): 바나나, 딜, 당근, 오이, 후무스

다음은 내림차순으로 정렬된 데이터의 몇 가지 예입니다.

  • 숫자: 100, 30, 12, 12, 9, 3, 1

  • 날짜: 2020-01-01, 1998-12-11, 1998-12-10, 1975-07-22

  • 단어(역 ASCII): 배,포도,사과,치즈

다음 하위 섹션에서는 이러한 정렬 기준을 지정하는 방법을 보여 줍니다.

오름차순 정렬을 지정하려면 Sorts.ascending() 정적 팩토리 메서드를 사용합니다. Sorts.ascending() 메서드에 오름차순으로 정렬해야 하는 필드의 이름을 전달합니다.

다음과 같이 sort() 메서드에 Sorts.ascending() 메서드의 출력을 전달하여 필드에 오름차순 정렬을 지정할 수 있습니다.

collection.find().sort(Sorts.ascending("<field name>"))

앞의 sort() 메서드는 지정된 필드 이름을 기준으로 가장 작은 것부터 큰 것 순으로 정렬하여 컬렉션의 문서를 반복할 수 있는 FindIterable 객체를 반환합니다.

다음 코드 예제에서는 ascending() 메서드를 사용하여 orderTotal 필드를 기준으로 샘플 컬렉션 을 정렬합니다.

val resultsFlow = collection.find()
.sort(Sorts.ascending(Order::orderTotal.name))
resultsFlow.collect { println(it) }
Order(id=6, date=2022-01-23, orderTotal=10.99, description=1 bagel, 1 orange juice, 1 muffin)
Order(id=1, date=2022-01-03, orderTotal=17.86, description=1/2 lb cream cheese and 1 dozen bagels)
Order(id=3, date=2022-01-11, orderTotal=19.49, description=1 dozen vanilla cupcakes)
Order(id=4, date=2022-01-15, orderTotal=43.62, description=2 chicken lunches and a diet coke)
Order(id=5, date=2022-01-23, orderTotal=60.31, description=one large vanilla and chocolate cake)
Order(id=2, date=2022-01-11, orderTotal=83.87, description=two medium vanilla birthday cakes)

내림차순 정렬을 지정하려면 Sorts.descending() 정적 팩토리 메서드를 사용합니다. 내림차순으로 정렬해야 하는 필드의 이름을 Sorts.descending() 메서드에 전달합니다.

다음 코드 스니펫은 orderTotal 필드에 내림차순 정렬을 지정하고 샘플 컬렉션 의 문서를 내림차순으로 반환하는 방법을 보여줍니다.

val resultsFlow = collection.find()
.sort(Sorts.descending(Order::orderTotal.name))
resultsFlow.collect { println(it) }
Order(id=2, date=2022-01-11, orderTotal=83.87, description=two medium vanilla birthday cakes)
Order(id=5, date=2022-01-23, orderTotal=60.31, description=one large vanilla and chocolate cake)
Order(id=4, date=2022-01-15, orderTotal=43.62, description=2 chicken lunches and a diet coke)
Order(id=3, date=2022-01-11, orderTotal=19.49, description=1 dozen vanilla cupcakes)
Order(id=1, date=2022-01-03, orderTotal=17.86, description=1/2 lb cream cheese and 1 dozen bagels)
Order(id=6, date=2022-01-23, orderTotal=10.99, description=1 bagel, 1 orange juice, 1 muffin)

결과를 정렬하는 데 사용하는 필드에 둘 이상의 문서에 동일한 값이 있는 경우 타이가 발생합니다. MongoDB는 타이가 발생할 경우 정렬 순서를 보장하지 않습니다. 예를 들어 다음 코드를 사용하여 샘플 컬렉션에 정렬을 적용할 때 타이가 발생한다고 가정해 보겠습니다.

collection.find().sort(Sorts.ascending(Order::date.name))

쿼리와 일치하는 여러 문서의 date 필드에 동일한 값이 포함되어 있으므로 문서가 일관된 순서로 반환되지 않을 수 있습니다.

값이 동일한 필드가 있는 문서에 대해 특정 순서를 보장해야 하는 경우, 이벤트가 발생할 경우 정렬할 추가 필드를 지정할 수 있습니다.

date 필드에 오름차순 정렬을 지정한 다음 orderTotal 필드에 오름차순 정렬을 지정하여 샘플 컬렉션 의 문서를 다음 순서로 반환할 수 있습니다.

collection.find().sort(Sorts.ascending(Order::date.name, Order::orderTotal.name))
Order(id=1, date=2022-01-03, orderTotal=17.86, description=1/2 lb cream cheese and 1 dozen bagels)
Order(id=3, date=2022-01-11, orderTotal=19.49, description=1 dozen vanilla cupcakes)
Order(id=2, date=2022-01-11, orderTotal=83.87, description=two medium vanilla birthday cakes)
Order(id=4, date=2022-01-15, orderTotal=43.62, description=2 chicken lunches and a diet coke)
Order(id=6, date=2022-01-23, orderTotal=10.99, description=1 bagel, 1 orange juice, 1 muffin)
Order(id=5, date=2022-01-23, orderTotal=60.31, description=one large vanilla and chocolate cake)

정렬 기준을 결합하려면 Sorts.orderBy() 정적 팩토리 메서드를 사용하세요. 이 메서드는 정렬된 정렬 기준 목록을 포함하는 객체를 생성합니다. 정렬을 수행할 때 이전 정렬 기준이 동점인 경우 목록의 다음 정렬 기준을 사용하여 순서를 결정합니다.

다음 코드 스니펫에서는 orderBy() 메서드를 사용하여 date 필드에서 내림차순 정렬을 수행하고, 동점인 경우 orderTotal 필드를 오름차순 정렬하여 데이터를 정렬합니다. 이러한 정렬 기준을 사용하면 코드는 샘플 컬렉션 의 문서를 다음 순서로 반환합니다.

val orderBySort = Sorts.orderBy(
Sorts.descending(Order::date.name), Sorts.ascending(Order::orderTotal.name)
)
val results = collection.find().sort(orderBySort)
results.collect {println(it) }
Order(id=6, date=2022-01-23, orderTotal=10.99, description=1 bagel, 1 orange juice, 1 muffin)
Order(id=5, date=2022-01-23, orderTotal=60.31, description=one large vanilla and chocolate cake)
Order(id=4, date=2022-01-15, orderTotal=43.62, description=2 chicken lunches and a diet coke)
Order(id=3, date=2022-01-11, orderTotal=19.49, description=1 dozen vanilla cupcakes)
Order(id=2, date=2022-01-11, orderTotal=83.87, description=two medium vanilla birthday cakes)
Order(id=1, date=2022-01-03, orderTotal=17.86, description=1/2 lb cream cheese and 1 dozen bagels)

컬렉션의 텍스트 인덱스 로 지정된 각 결과 필드의 값이 Atlas Search 과 얼마나 일치하는지를 기준으로 string 텍스트 Atlas Search 결과의 순서를 지정할 수 string 있습니다. 텍스트 Atlas Search는 각 결과가 Atlas Search string 과 얼마나 일치하는지를 나타내는 숫자 텍스트 점수 를 할당합니다. Sorts.metaTextScore() 정적 팩토리 메서드를 사용하여 텍스트 점수를 기준으로 정렬하는 정렬 기준을 작성합니다.

중요

텍스트 인덱스 생성 확인

다음 코드 예시에서는 Sorts.metaTextScore() 메서드를 사용하여 샘플 컬렉션에서 텍스트 검색 결과를 정렬하는 방법을 보여 줍니다. 이 코드 예시에서는 필터, 인덱스프로젝션 빌더를 사용합니다.

이 코드 예제에서는 다음 조치를 수행합니다.

  1. description 필드에 샘플 컬렉션 에 대한 텍스트 인덱스를 생성합니다. 컬렉션에 이미 존재하는 인덱스를 지정하여 createIndex() 를 호출하면 작업을 통해 새 인덱스가 생성되지 않습니다.

  2. "vanilla" 구문에 대한 텍스트 검색을 실행합니다.

  3. 텍스트 점수를 쿼리 결과에 score 필드로 프로젝션합니다.

  4. 텍스트 점수를 기준으로 결과를 정렬합니다(가장 일치하는 항목 먼저).

데이터는 다음 Kotlin 데이터 클래스로 모델링됩니다.

data class OrderScore(
@BsonId val id: Int,
val description: String,
val score: Double
)
import com.mongodb.client.model.Sorts
import com.mongodb.client.model.Projections
import com.mongodb.client.model.Filters
import com.mongodb.client.model.Indexes
collection.createIndex(Indexes.text(Order::description.name))
val metaTextScoreSort = Sorts.orderBy(
Sorts.metaTextScore(OrderScore::score.name),
Sorts.descending("_id")
)
val metaTextScoreProj = Projections.metaTextScore(OrderScore::score.name)
val searchTerm = "vanilla"
val searchQuery = Filters.text(searchTerm)
val results = collection.find<OrderScore>(searchQuery)
.projection(metaTextScoreProj)
.sort(metaTextScoreSort)
results.collect { println(it) }
OrderScore(id=3, description=1 dozen vanilla cupcakes, score=0.625)
OrderScore(id=5, description=one large vanilla and chocolate cake, score=0.6)
OrderScore(id=2, description=two medium vanilla birthday cakes, score=0.6)

참고

Atlas Search 이상에서 텍스트 동작 MongoDB 4.4

MongoDB 4.4 이상에서는 텍스트 검색의 구조가 변경되었습니다. 더 이상 텍스트 점수를 기준으로 정렬하기 위해 Projections.metaTextScore()FindFlow 인스턴스에 투영할 필요가 없습니다. 또한 정렬에 사용되는 $meta 텍스트 점수 애그리게이션 작업에서 지정한 필드 이름은 무시됩니다. 즉, Sorts.metaTextScore() 에 전달한 필드 이름 인수가 무시됩니다.

이 섹션의 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.

자세한 내용은 Sorts 클래스 를 참조하세요. API 문서. $text 쿼리 연산자 및 $meta 집계 파이프라인 연산자에 대한 자세한 내용은 서버 매뉴얼 문서를 참조하세요.

돌아가기

Change Stream 열기

다음

반환된 결과 건너뛰기