Retrieve Data
개요
이 가이드 에서는 코틀린 동기 (Kotlin Sync) 운전자 를 사용하여 읽기 작업을 통해 MongoDB 컬렉션 에서 데이터를 조회 하는 방법을 학습 수 있습니다. find()
메서드를 호출하여 쿼리 필터하다 에 지정된 설정하다 과 일치하는 문서를 조회 할 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트 의
sample_restaurants
데이터베이스 에 있는 restaurants
컬렉션 을 사용합니다. 무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 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) }
Restaurant(name=Tropicoso Club, cuisine=Spanish) Restaurant(name=Beso, cuisine=Spanish) Restaurant(name=Sabor Latino Restaurant, cuisine=Spanish) ...
참고
모든 문서 찾기
컬렉션의 모든 문서를 찾으려면 find()
메서드에 빈 필터를 전달합니다.
val results = collection.find()
검색 동작 수정
메서드를 find()
메서드 호출에 연결하여 find()
메서드의 동작을 수정할 수 있습니다. 다음 표에서는 쿼리 수정에 일반적으로 사용되는 메서드에 대해 설명합니다.
메서드 | 설명 |
---|---|
| Limits the number of documents to return per batch. To learn more about
batch size, see cursor.batchSize()
in the MongoDB Server manual. |
| Sets the collation options for the query. |
| 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. |
| Specifies the index to use for the query. |
| Limits the number of documents to be returned from the query. |
| Sets the number of documents to skip. |
| Defines the sort criteria to apply to the query. |
The following example chains the limit()
method to limit the
number of documents returned by the query to 10
:
val results = collection .find(eq(Restaurant::cuisine.name, "Spanish")) .limit(10)
의 동작을 수정하는 find()
메서드의 전체 목록은 API 설명서 를 FindIterable
참조하세요. 클래스의 경우.
추가 정보
쿼리 필터에 대해 자세히 알아보려면 쿼리 지정을 참조하세요.
To view runnable code examples that retrieve documents by using the Kotlin Sync driver, see 데이터 읽기.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.