개요
이 가이드 에서는 MongoDB database 에서 문서를 조회 방법을 학습 수 있습니다. 다음을 사용하여 문서를 찾을 수 있습니다.
찾기 작업을 사용하여 컬렉션에서 문서의 하위 집합 검색
애그리게이션 작업을 사용하여 컬렉션에서 검색된 문서에서 변환 수행
변경 스트림을 사용하여 데이터베이스의 실시간 변경 사항 모니터링
예시용 샘플 데이터
다음 섹션에서는 페인트 매장 주인이 고객 주문을 관리하는 방법에 대한 예를 제공합니다. 각 주문에 대해 주인은 paint_order 컬렉션의 color 및 qty 필드에서 색상과 수량을 추적합니다.
{ "_id": 1, "color": "purple", "qty": 10 } { "_id": 2, "color": "green", "qty": 8 } { "_id": 3, "color": "purple", "qty": 4 } { "_id": 4, "color": "green", "qty": 11 }
찾기 작업
찾기 작업을 사용하여 MongoDB 에서 문서를 조회 . 조회 할 문서, 조회 순서, 조회 할 문서 수를 지정할 수 있습니다.
MongoCollection 인스턴스 에서 find() 메서드를 호출하여 제공된 쿼리 와 일치하는 문서를 필터하다 합니다. 쿼리 지정하는 방법에 대한 자세한 내용은 쿼리 지정 가이드 참조하세요.
그런 다음 forEach() 또는 cursor() 와 같은 메서드를 사용하여 일치하는 문서를 조회 할 수 있습니다. 자세한 내용은 FindIterable API 설명서를 참조하세요.
단일 문서 조회 하려면 find() 호출에 first() 메서드를 추가하면 됩니다. 특정 문서 선택하려면 첫 번째 문서 선택하기 전에 sort() 작업을 사용할 수 있습니다. limit() 메서드를 사용하여 메모리 사용량을 최적화할 수도 있습니다. 정렬 작업을 사용할 때 메모리 최적화에 대한 자세한 내용은 서버 매뉴얼을 참조하세요.
예시
주인은 paint_order 컬렉션에서 3개 이상 9개 미만의 페인트 캔이 포함된 주문을 알고 싶습니다.
이 시나리오를 해결하기 위해 매장 주인은 기준과 일치하는 주문을 찾습니다.
Bson filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9)); // Retrieves documents that match the filter and prints them as JSON collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
필터 작성 방법에 대한 자세한 내용은 필터 빌더 가이드를 참조하세요.
다음은 앞선 쿼리의 출력입니다:
{ "_id": 2, "color": "green", "qty": 8 } { "_id": 3, "color": "purple", "qty": 4 }
매장 주인이 이 쿼리를 실행하면 기준과 일치하는 두 개의 주문이 검색됩니다.
찾기 예시: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기단계에 따라 MongoDB Atlas 의 프리 티어 에서 데이터베이스 에 로드할 수 있습니다.
이 예시 다음 조치를 수행하는 완전한 독립형 파일 입니다.
find()메서드를 호출하여runtime값이15분 미만인 10 문서를 조회 결과에 프로젝션 및 정렬을 적용합니다.find()및first()메서드를 호출하여runtime값이15분 미만인 가장 높은imdb.rating의 문서 조회 결과에 프로젝션 적용합니다.
// Retrieves documents that match a query filter by using the Java driver package org.example; 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; import static com.mongodb.client.model.Filters.eq; 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"); // Projects "title" and "imdb" fields, excludes "_id" Bson projectionFields = Projections.fields( Projections.include("title", "imdb"), Projections.excludeId()); // Retrieves documents with a runtime of less than 15 minutes, applying the // projection and a sorting in alphabetical order FindIterable<Document> docs = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("title")) .limit(10); // Prints the titles of the queried documents System.out.println("10 movies under 15 minutes: "); docs.forEach(doc -> System.out.println("- " + doc.get("title"))); System.out.println(); // Retrieves the document with the best imdb rating that is less // than 15 minutes long, applying the projection Document doc = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("imdb.rating")) .first(); // Prints title of the queried document if (doc == null) { System.out.println("No results found."); } else { System.out.println("The highest rated movie under 15 minutes: " + doc.toJson().get("title")); } } } }
10 movies under 15 minutes: 10 Minutes, 3x3, 7:35 in the Morning, 8, 9, A Chairy Tale, A Corner in Wheat, A Gentle Spirit, A Is for Autism, A Movie, The highest rated movie under 15 minutes: {"title": "Andrè and Wally B.", "imdb": {"rating": 5.4, "votes": 3294, "id": 86855}}
애그리게이션 작업
집계 작업을 사용하여 집계 파이프라인의 단계를 수행합니다. 집계 파이프라인은 집계된 결과를 생성하는 다단계 변환입니다.
애그리게이션 작업을 수행하려면 MongoCollection의 인스턴스 에서 aggregate() 메서드를 호출합니다. 이 메서드는 순서대로 실행 집계 표현식을 허용합니다. 애그리게이션을 수행하기 위해 문서를 일치시키고, 필드의 이름을 바꾸고, 값을 그룹 하는 방법을 지정하는 집계 단계를 정의할 수 있습니다. 자세한 내용은 애그리게이션 가이드 및 애그리게이션 표현식 작업 페이지를 참조하세요.
예시
소유자는 paint_order 컬렉션에서 가장 많이 구매된(가장 많이 판매된) 페인트 색상을 알고 싶어합니다.
이 시나리오를 해결하기 위해 매장 주인은 다음과 같은 집계 파이프라인을 만듭니다.
paint_order컬렉션의 모든 문서와 일치색상별로 주문 그룹화
색상별로 수량 필드 합산
결과 순서를 가장 높은 수량에서 가장 낮은 수량 순으로 지정
Bson filter = Filters.empty(); // Prints the collection's "color" values and each value's frequency in descending frequency order collection.aggregate(Arrays.asList( Aggregates.match(filter), Aggregates.group("$color", Accumulators.sum("qty", "$qty")), Aggregates.sort(Sorts.descending("qty")))) .forEach(doc -> System.out.println(doc.toJson()));
다음은 앞에 설명한 집계 결과를 보여줍니다.
{ "_id": "green", "qty": 19 } { "_id": "purple", "qty": 14 }
매장 주인이 집계를 실행한 후 '녹색'이 가장 많이 구매된 색상이라는 것을 알게 됩니다.
집계 파이프라인을 구성하는 방법에 대한 자세한 내용은 애그리게이션에 대한 MongoDB Server 매뉴얼 페이지를 참조하세요 .
추가 정보
API 문서
이 페이지에서 문서를 조회 데 사용되는 메서드 및 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.