Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Java Reactive Streams 드라이버
/

쿼리 지정

이 가이드 에서는 Java Reactive Streams 운전자 를 사용하여 쿼리 를 지정하는 방법을 학습 수 있습니다.

중요

프로젝트 리액터 라이브러리

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.

This guide uses the Flux Publisher, which is a Publisher implementation from the Project Reactor library. In Java Reactive Streams, you must use Publisher implementations to control how data is transmitted in your application. To learn more about the Flux class, see Flux in the Project Reactor documentation.

쿼리 필터 를 만들어 쿼리가 반환하는 문서 세트를 구체화할 수 있습니다. 쿼리 필터는 MongoDB 가 읽기 또는 쓰기 작업에서 문서를 일치시키는 데 사용하는 Atlas Search 기준을 지정하는 표현식입니다. 쿼리 필터에서는 드라이버가 쿼리와 정확히 일치하는 문서를 Atlas Search에 표시하도록 요청하거나 쿼리 필터를 Express 하여 보다 복잡한 일치 기준을 표현할 수 있습니다.

이 가이드 의 예제에서는 다음 문서가 포함된 fruits 컬렉션 에서 작업을 실행 합니다.

{ "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },
{ "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },

다음 코드 예시에서는 데이터베이스와 컬렉션을 만든 다음 컬렉션에 샘플 문서를 삽입하는 방법을 보여 줍니다.

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerApi;
import com.mongodb.ServerApiVersion;
import com.mongodb.client.result.InsertManyResult;
import org.bson.Document;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.reactivestreams.client.MongoCollection;
import java.util.Arrays;
import java.util.List;
public class QueryDatabase {
public static void main(String[] args) {
// Replace the placeholder with your Atlas connection string
String uri = "<connection string>";
// Construct a ServerApi instance using the ServerApi.builder() method
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
// Create a new client and connect to the server
try (MongoClient mongoClient = MongoClients.create(settings)) {
MongoDatabase database = mongoClient.getDatabase("sample_fruits");
MongoCollection<Document> fruits = database.getCollection("fruits");
Document document1 = new Document("_id", "1")
.append("name", "apples")
.append("qty", 5)
.append("rating", 3)
.append("color", "red")
.append("type", Arrays.asList("fuji", "honeycrisp"));
Document document2 = new Document("_id", "2")
.append("name", "bananas")
.append("qty", 7)
.append("rating", 4)
.append("color", "yellow")
.append("type", Arrays.asList("cavendish"));
Document document3 = new Document("_id", "3")
.append("name", "oranges")
.append("qty", 6)
.append("rating", 2)
.append("type", Arrays.asList("naval", "mandarin"));
Document document4 = new Document("_id", "4")
.append("name", "pineapple")
.append("qty", 3)
.append("rating", 5)
.append("color", "yellow");
List<Document> documents = Arrays.asList(document1, document2, document3, document4);
Publisher<InsertManyResult> insertPublisher = fruits.insertMany(documents);
Mono.from(insertPublisher).block();
}
}
}

리터럴 값 쿼리는 쿼리 필터하다 와 정확히 일치하는 문서를 반환합니다. 정확히 일치하는 문서를 반환하려면 eq() 비교 연산자 메서드를 사용합니다.

다음 예시 에서는 eq() 비교 연산자 메서드를 find() 메서드의 쿼리 필터하다 매개 변수로 지정합니다. 이 코드는 color 필드 값이 "yellow" 인 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(eq("color", "yellow"));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

모든 문서 찾기

컬렉션 의 모든 문서를 찾으려면 매개변수를 지정하지 않고 find() 메서드를 호출합니다. 다음 예시 에서는 컬렉션 의 모든 문서를 찾습니다.

FindPublisher<Document> findDocPublisher = fruits.find();
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();

비교 연산자는 쿼리 필터하다 에 지정된 값을 기준으로 문서 필드 값을 평가합니다. 다음은 일반적인 비교 연산자 메서드 목록입니다.

  • gt(): 보다 큼

  • lte(): 보다 작거나 같음

  • ne(): 같지 않음

비교 연산자의 전체 목록을 보려면 MongoDB Server 매뉴얼의 비교 쿼리 연산자 가이드를 참조하세요.

다음 예시 에서는 쿼리 필터하다 의 gt() 비교 연산자 메서드를 find() 메서드에 대한 매개 변수로 지정합니다. 이 코드는 rating 필드 값이 2 보다 큰 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(gt("rating", 2));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

논리 연산자는 두 개 이상의 표현식 집합의 결과에 적용된 논리를 사용하여 문서를 일치시킵니다. 다음은 논리 연산자 메서드 목록입니다.

  • and()모든 절의 조건과 일치하는 모든 문서를 반환합니다.

  • or() 절의 조건과 일치하는 모든 문서를 반환합니다.

  • nor(), 어떤 절의 조건과도 일치 하지 않는 모든 문서를 반환합니다.

  • not()표현식과 일치 하지 않는 모든 문서를 반환합니다.

논리 연산자에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 논리 쿼리 연산자 가이드를 참조하세요.

다음 예시 에서는 쿼리 필터하다 의 or() 논리 연산자 메서드를 find() 메서드에 대한 매개 변수로 지정합니다. 이 코드는 qty 필드 값이 5 보다 크 거나 color 필드 값이 "yellow" 인 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(
or(gt("qty", 5), eq("color", "yellow")));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

배열 연산자는 배열 필드 에 있는 요소의 값 또는 수량을 기준으로 문서를 일치시킵니다. 다음은 사용 가능한 배열 연산자 메서드 목록입니다.

  • all()쿼리의 모든 요소를 포함하는 배열이 있는 문서를 반환합니다.

  • elemMatch()배열 필드의 요소가 쿼리의 모든 조건과 일치하는 경우 문서를 반환합니다.

  • size()지정된 크기의 배열이 있는 모든 문서를 반환합니다.

배열 연산자에 대해 자세히 알아보려면 매뉴얼의 배열 쿼리 연산자 가이드를 MongoDB Server 참조하세요.

다음 예시 에서는 쿼리 필터하다 의 size() 배열 연산자 메서드를 find() 메서드에 대한 매개 변수로 지정합니다. 이 코드는 2 요소를 포함하는 type 배열 필드 가 있는 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(size("type", 2));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}

요소 연산자는 필드 의 존재 여부 또는 유형에 따라 데이터를 쿼리 합니다. 다음은 사용 가능한 요소 연산자 메서드 목록입니다.

  • exists()지정된 필드 가 있는 문서를 반환합니다.

  • type()필드 가 지정된 유형인 경우 문서를 반환합니다.

요소 연산자에 대해 자세히 알아보려면 매뉴얼의 요소 쿼리 연산자 가이드를 MongoDB Server 참조하세요.

다음 예시 에서는 쿼리 필터하다 의 exists() 요소 연산자 메서드를 find() 메서드에 대한 매개 변수로 지정합니다. 이 코드는 color 필드 가 있는 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(exists("color", true));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

평가 연산자는 개별 필드 또는 전체 컬렉션 문서의 평가를 기반으로 데이터를 반환합니다. 다음은 일반적인 평가 연산자 메서드 목록입니다.

  • text(), which performs a text query on the documents

  • regex()지정된 정규 표현식과 일치하는 문서를 반환합니다.

  • mod(), which performs a modulo operation on the value of a field and returns documents where the remainder is a specified value

평가 연산자의 전체 목록을 보려면 MongoDB Server 매뉴얼의 평가 쿼리 연산자 가이드를 참조하세요.

다음 예시 에서는 쿼리 필터하다 의 regex() 평가 연산자 메서드를 find() 메서드에 대한 매개 변수로 지정합니다. 이 코드는 정규 표현식 을 사용하여 "p" 문자가 두 개 이상 연속된 name 필드 값이 있는 모든 문서를 반환합니다.

FindPublisher<Document> findDocPublisher = fruits.find(regex("name", "p{2,}"));
Document findResults = Flux.from(findDocPublisher)
.doOnNext(System.out::println)
.blockLast();
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}
{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

문서 쿼리에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 쿼리 가이드를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

데이터 읽기

이 페이지의 내용