문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Java 동기화 드라이버

여러 문서 찾기

MongoCollection 객체에서 find() 메서드를 호출하여 컬렉션에 있는 여러 문서를 쿼리할 수 있습니다. 컬렉션의 필터와 일치하는 문서를 쿼리하고 반환하려면 쿼리 필터를 find() 메서드에 전달합니다. 필터를 포함하지 않으면 MongoDB는 컬렉션의 모든 문서를 반환합니다.

Java 드라이버로 MongoDB를 쿼리하는 방법에 대한 자세한 내용은 문서 쿼리에 대한 가이드를 참조하세요.

일치하는 문서를 지정된 순서대로 정리하는 sort(), 반환된 문서에 포함할 필드를 구성하는 projection() 등의 메서드를 find() 메서드에 연결할 수도 있습니다.

sort() 메서드에 대한 자세한 내용은 정렬 가이드를 참조하세요. projection() 메서드에 대한 자세한 내용은 프로젝션 가이드를 참조하세요.

find() 메서드는 결과에 액세스, 구성 및 탐색할 수 있는 여러 매서드를 제공하는 클래스인 FindIterable의 인스턴스를 반환합니다. 또한 FindIterable은(는) 핵심 Java 인터페이스 Iterable을(를) 구현하는 상위 클래스인 MongoIterable의 메서드를 상속합니다.

MongoIterable에서 iterator() 메서드를 호출하여 결과를 탐색하는 데 사용할 수 있는 MongoCursor 인스턴스를 반환할 수 있습니다. MongoCursor에서 메서드(예: hasNext())를 호출하여 추가 결과가 있는지 확인하거나 next()을(를) 호출하여 collection의 다음 문서를 반환할 수 있습니다. 쿼리와 일치하는 문서가 없는 경우 hasNext()을(를) 호출하면 false이(가) 반환되므로 next()을(를) 호출하면 예외가 발생합니다.

최종 결과를 반환한 후 또는 반환된 결과가 없는 경우 반복기(iterator)에서 next()를 호출하면 java.util.NoSuchElementException 유형의 예외가 발생합니다. next()를 호출하기 전에 항상 hasNext()를 사용하여 추가 결과가 있는지 확인합니다.

다음 스니펫은 movies 컬렉션의 쿼리와 일치하는 모든 문서를 찾아서 출력합니다. 다음 객체와 메서드를 사용합니다:

  • find() 메서드에 전달되는 쿼리 필터입니다. lt() 필터는 런타임이 15분 미만인 영화만 일치합니다.

  • 반환된 문서를 제목별로 내림차순으로 정리하는 정렬('Z'가 'A' 앞에 위치).

  • 헬퍼 메서드 excludeId()를 사용하여 titleimdb 필드의 객체를 포함하고 _id 필드를 제외하는 프로젝션.

참고

이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스 연결에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

// Retrieves documents that match a query filter by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.lt;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
public class Find {
public static void main( String[] args ) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// Creates instructions to project two document fields
Bson projectionFields = Projections.fields(
Projections.include("title", "imdb"),
Projections.excludeId());
// Retrieves documents that match the filter, applying a projection and a descending sort to the results
MongoCursor<Document> cursor = collection.find(lt("runtime", 15))
.projection(projectionFields)
.sort(Sorts.descending("title")).iterator();
// Prints the results of the find operation as JSON
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
}
}

레거시 API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 API 설명서를 참조하세요.

  • FindIterable

  • MongoIterable

  • MongoCursor

  • find()

← 문서 찾기