Docs Menu
Docs Home
/ / /
Java 동기화 드라이버
/ /

문서 찾기

MongoCollection 객체에서 find() 메서드와 first() 메서드를 함께 연결하여 컬렉션에서 단일 문서를 검색할 수 있습니다. 쿼리 필터를 find() 메서드에 전달하여 컬렉션의 필터와 일치하는 문서를 쿼리하고 반환할 수 있습니다. 필터를 포함하지 않으면 MongoDB는 컬렉션의 모든 문서를 반환합니다. first() 메서드는 일치하는 첫 번째 문서를 반환합니다.

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

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

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

find() 메서드는 결과에 액세스, 구성, 탐색을 위한 여러 메서드를 제공하는 클래스인 FindIterable 인스턴스를 반환합니다. FindIterablefirst()와 같은 상위(parent) 클래스의 MongoIterable 메서드도 상속합니다.

first() 메서드는 검색된 결과에서 첫 번째 문서를 반환하거나 결과가 없는 경우 null을 반환합니다.

다음 스니펫은 movies 컬렉션에서 단일 문서를 찾습니다. 다음 객체와 메서드를 사용합니다:

  • find() 메서드에 전달되는 쿼리 필터입니다 . eq 필터는 제목이 'The Room' 텍스트와 정확히 일치하는 영화만 일치합니다.

  • 일치하는 문서를 등급별 내림차순으로 정리하는 정렬입니다. 쿼리가 여러 문서와 일치하는 경우 반환되는 문서는 등급이 가장 높은 문서입니다.

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

참고

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

// Retrieves a document that matches a query filter by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
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.MongoDatabase;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
public class FindOne {
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 the first matching document, applying a projection and a descending sort to the results
Document doc = collection.find(eq("title", "The Room"))
.projection(projectionFields)
.sort(Sorts.descending("imdb.rating"))
.first();
// Prints a message if there are no result documents, or prints the result document as JSON
if (doc == null) {
System.out.println("No results found.");
} else {
System.out.println(doc.toJson());
}
}
}
}

Legacy API

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

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

  • FindIterable

  • MongoIterable

  • find()

  • first()

돌아가기

작업 찾기