문서 메뉴
문서 홈
/ / /
Kotlin Sync 드라이버
/

데이터 조회

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 문서 찾기
  • 문서 찾기 예시
  • 검색 동작 수정
  • 추가 정보
  • API 문서

이 가이드에서는 Kotlin Sync 드라이버를 사용하여 읽기 작업을 통해 MongoDB 컬렉션에서 데이터를 검색하는 방법을 배울 수 있습니다. find() 메서드를 호출하여 쿼리 필터에 지정된 기준 세트와 일치하는 문서를 검색할 수 있습니다.

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

이 컬렉션의 문서는 다음 Kotlin 데이터 클래스에 따라 모델링됩니다.

data class Restaurant(
val name: String,
val cuisine: String
)

find() 메서드는 컬렉션에서 문서를 검색합니다. 이 메서드는 쿼리 필터 를 사용하여 일치하는 모든 문서를 반환합니다. 쿼리 필터는 드라이버가 컬렉션의 문서를 일치시키는 데 사용하는 기준을 지정하는 문서입니다.

쿼리 필터에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.

다음 예제에서는 find() 메서드를 사용하여 cuisine 필드의 값이 "Spanish" 인 모든 문서를 찾습니다.

val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))

앞의 예시에서 find() 작업은 FindIterable 객체를 반환하며, 다음 예시와 같이 forEach() 메서드를 사용하여 객체를 반복할 수 있습니다.

val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
results.forEach { result ->
println(result)
}

참고

모든 문서 찾기

컬렉션의 모든 문서를 찾으려면 find() 메서드에 빈 필터를 전달합니다.

val results = collection.find()

메서드를 find() 메서드 호출에 연결하여 find() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 쿼리 수정에 일반적으로 사용되는 메서드에 대해 설명합니다.

메서드
설명
batchSize()
Limits the number of documents to return per batch. To learn more about batch size, see cursor.batchSize() in the MongoDB Server manual.
collation()
Sets the collation options for the query.
comment()
Specifies a string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data. To learn more about query comments, see $comment in the MongoDB Server manual.
hint()
Specifies the index to use for the query.
limit()
Limits the number of documents to be returned from the query.
maxTime()
Sets the maximum execution time on the server for this operation.
skip()
Sets the number of documents to skip.
sort()
Defines the sort criteria to apply to the query.

다음 예에서는 limit()maxTime() 메서드를 연결하여 쿼리에서 반환되는 문서 수를 10 로 제한하고 작업의 최대 실행 시간을 10000 밀리초로 설정합니다.

val results = collection
.find(eq(Restaurant::cuisine.name, "Spanish"))
.limit(10)
.maxTime(10000)

의 동작을 수정하는 find() 메서드의 전체 목록은 API 설명서 를 FindIterable 참조하세요. 클래스의 경우.

쿼리 필터에 대해 자세히 알아보려면 쿼리 지정을 참조하세요.

Kotlin Sync 드라이버를 사용하여 문서를 검색하는 실행 가능한 코드 예제를 보려면 MongoDB에서 데이터 읽기를 참조하세요.

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

돌아가기

쿼리 지정

다음

반환할 필드 지정