문서 메뉴
문서 홈
/ / /
Java Reactive Streams 드라이버
/

읽기 작업

이 페이지의 내용

  • 전제 조건
  • MongoDB 배포에 연결하기
  • 컬렉션 쿼리
  • 쿼리 필터
  • 빈 필터
  • 필터 헬퍼
  • FindPublisher
  • 프로젝션
  • 정렬
  • 프로젝션으로 정렬
  • 설명합니다.
  • 읽기 설정
  • readConcern

읽기 작업은 컬렉션에서 문서 또는 문서에 대한 정보를 검색합니다. 필터를 지정하여 필터 조건과 일치하는 문서만 조회할 수 있습니다.

이 가이드의 코드 예제를 실행하려면 다음 구성 요소를 설정해야 합니다.

  • test.restaurants restaurants.json 문서 자산 에 있는 파일의 문서로 채워진 컬렉션입니다.Github

  • 다음 가져오기 문:

import com.mongodb.*;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import java.util.Arrays;
import org.bson.Document;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;

중요

이 가이드에서는 퀵 스타트 프라이머에 설명된 Subscriber 구현을 사용합니다.

먼저 MongoDB deployment에 연결한 다음 MongoDatabaseMongoCollection 인스턴스를 선언하고 정의합니다.

다음 코드는 포트 27017localhost 에서 실행되는 독립형 MongoDB 배포서버에 연결합니다. 그런 다음 test 데이터베이스를 참조하는 database 변수와 restaurants 컬렉션을 참조하는 collection 변수를 정의합니다.

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("restaurants");

MongoDB deployment에 연결하는 방법에 대해 자세히 알아보려면 MongoDB에 연결 튜토리얼을 참조하세요.

컬렉션을 쿼리하려면 컬렉션의 find() 메서드를 사용할 수 있습니다.

인수 없이 메서드를 호출하여 컬렉션의 모든 문서를 쿼리할 수 있습니다.

collection.find().subscribe(new PrintDocumentSubscriber());

또는 필터를 전달하여 필터 기준과 일치하는 문서를 쿼리할 수 있습니다.

collection.find(eq("name", "456 Cookies Shop"))
.subscribe(new PrintDocumentSubscriber());

특정 조건과 일치하는 문서를 쿼리하려면 필터 문서를 find() 메서드에 전달합니다.

빈 필터를 지정하고 컬렉션의 모든 문서를 일치시키려면 빈 Document 객체를 사용합니다.

collection.find(new Document()).subscribe(new PrintDocumentSubscriber());

find() 메서드를 사용하는 경우 컬렉션의 모든 문서와 일치하도록 필터 객체를 전달하지 않고 메서드를 호출할 수도 있습니다.

collection.find().subscribe(new PrintDocumentSubscriber());

필터 문서를 쉽게 만들 수 있도록 드라이버는 필터 조건 헬퍼 메서드를 제공하는 Filters 클래스를 제공합니다.

이 찾기 작업 예시에는 다음 조건을 지정하는 필터 Document 인스턴스가 포함되어 있습니다.

  • stars 필드 값이 2 이상이고 5미만입니다.

  • categories 필드가 "Bakery"와 같거나 categories 이 배열 필드인 경우 string "Bakery" 를 요소로 포함합니다.

collection.find(
new Document("stars", new Document("$gte", 2)
.append("$lt", 5))
.append("categories", "Bakery")).subscribe(new PrintDocumentSubscriber());

다음 예제에서는 Filters 헬퍼 메서드를 사용하여 동일한 필터 조건을 지정합니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.subscribe(new PrintDocumentSubscriber());

쿼리 필터 연산자 목록을 보려면 MongoDB Server 매뉴얼에서 쿼리 및 프로젝션 연산자 를 참조하세요. 헬퍼목록을 보려면 필터 Filters API 설명서를 참조하세요.

find() 메서드는 FindPublisher 인터페이스의 인스턴스를 반환합니다. 이 인터페이스는 find() 메서드에 연결하여 sort() 또는 projection() 와 같이 쿼리의 출력이나 동작을 수정하고 subscribe() 메서드를 통해 결과를 반복할 수 있는 다양한 메서드를 제공합니다.

기본적으로 MongoDB의 쿼리는 일치하는 문서의 모든 필드를 반환합니다. 일치하는 문서에서 반환할 필드를 지정하기 위해 프로젝션 문서를 지정할 수 있습니다.

이 찾기 작업 예제에는 일치하는 문서에 name, starscategories 필드만 포함하도록 지정하는 프로젝션 Document 가 포함되어 있습니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.projection(new Document("name", 1)
.append("stars", 1)
.append("categories",1)
.append("_id", 0))
.subscribe(new PrintDocumentSubscriber());

프로젝션 문서를 쉽게 만들 수 있도록 드라이버는 Projections 클래스를 제공합니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.projection(fields(include("name", "stars", "categories"), excludeId()))
.subscribe(new PrintDocumentSubscriber());

프로젝션 문서에서 프로젝션 연산자를 사용하여 프로젝션 표현식을 지정할 수도 있습니다.

Projections.metaTextScore() 메서드를 사용하는 예제를 보려면 Text Atlas Search 튜토리얼을 참조하세요.

문서를 정렬하려면 정렬 사양 문서를 FindPublisher.sort() 메서드에 전달합니다. 드라이버는 정렬 사양 문서를 쉽게 만들 수 있도록 Sorts 헬퍼 메서드를 제공합니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.sort(Sorts.ascending("name"))
.subscribe(new PrintDocumentSubscriber());

FindPublisher 메서드 자체는 FindPublisher 객체를 반환하므로 find() 메서드에 여러 FindPublisher 메서드를 추가할 수 있습니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.sort(Sorts.ascending("name"))
.projection(fields(include("name", "stars", "categories"), excludeId()))
.subscribe(new PrintDocumentSubscriber());

찾기 작업을 설명하려면 FindPublisher.explain() 메서드를 호출합니다.

collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
.explain()
.subscribe(new PrintDocumentSubscriber());

복제본 세트 또는 샤드 클러스터에 대한 읽기 작업의 경우 다음 수준에서 읽기 설정을 구성할 수 있습니다.

  • 다음과 같은 방법으로 MongoClient 에서:

    • MongoClientSettings 인스턴스를 생성합니다.

      MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
      .applyConnectionString(new ConnectionString("mongodb://host1,host2"))
      .readPreference(ReadPreference.secondary())
      .build());
    • ConnectionString 인스턴스를 생성합니다.

      MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readPreference=secondary");
  • withReadPreference() 메서드를 사용하여 MongoDatabase 에서:

    MongoDatabase database = mongoClient.getDatabase("test")
    .withReadPreference(ReadPreference.secondary());
  • withReadPreference() 메서드를 사용하여 MongoCollection 에서:

    MongoCollection<Document> collection = database.getCollection("restaurants")
    .withReadPreference(ReadPreference.secondary());

MongoDatabase MongoCollection 인스턴스는 변경할 수 없습니다. 기존 MongoDatabase 또는 MongoCollection 인스턴스에서 withReadPreference() 를 호출하면 새 인스턴스가 반환되며 메서드가 호출되는 인스턴스에는 영향을 주지 않습니다.

다음 예제에서 collectionWithReadPref 인스턴스의 읽기 기본 설정은 primaryPreferred 인 반면, collection 의 읽기 기본 설정은 영향을 받지 않습니다.

MongoCollection<Document> collectionWithReadPref = collection.withReadPreference(ReadPreference.primaryPreferred());

복제본 세트 또는 샤드 클러스터에 대한 읽기 작업의 경우 애플리케이션은 다음 수준에서 읽기 고려를 구성할 수 있습니다.

  • 다음과 같은 방법으로 MongoClient 에서:

    • MongoClientSettings 인스턴스를 생성합니다.

      MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
      .applyConnectionString(new ConnectionString("mongodb://host1,host2"))
      .readConcern(ReadConcern.MAJORITY)
      .build());
    • ConnectionString 인스턴스를 생성합니다.

      MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readConcernLevel=majority");
  • withReadConcern() 메서드를 사용하여 MongoDatabase 에서:

    MongoDatabase database = mongoClient.getDatabase("test")
    .withReadConcern(ReadConcern.MAJORITY);
  • withReadConcern() 메서드를 사용하여 MongoCollection 에서:

    MongoCollection<Document> collection = database.getCollection("restaurants")
    .withReadConcern(ReadConcern.MAJORITY);

MongoDatabase MongoCollection 인스턴스는 변경할 수 없습니다. 기존 MongoDatabase 또는 MongoCollection 인스턴스에서 withReadConcern() 를 호출하면 새 인스턴스가 반환되며 메서드가 호출되는 인스턴스에는 영향을 주지 않습니다.

다음 예제에서 collWithReadConcern 인스턴스에는 AVAILABLE 읽기 고려가 있는 반면 인스턴스의 읽기 collection 고려는 영향을 받지 않습니다.

MongoCollection<Document> collWithReadConcern = collection.withReadConcern(ReadConcern.AVAILABLE);

읽기 고려, 읽기 설정 및 쓰기 고려의 조합을 포함하도록 MongoClientSettings, MongoDatabase 또는 MongoCollection 인스턴스를 빌드할 수 있습니다.

예를 들어 다음 코드는 컬렉션 수준에서 이 세 가지를 모두 설정합니다.

collection = database.getCollection("restaurants")
.withReadPreference(ReadPreference.primary())
.withReadConcern(ReadConcern.MAJORITY)
.withWriteConcern(WriteConcern.MAJORITY);

돌아가기

인덱스 만들기

다음

클라이언트 측 암호화