文档菜单
文档首页
/ / /
Java 反应式流驱动程序
/

指定查询

在本页

  • 概述
  • 示例数据
  • 精确匹配
  • 比较运算符
  • 逻辑运算符
  • 数组运算符
  • 元素运算符
  • 评估运算符
  • 附加信息
  • API 文档

在本指南中,您可以通过使用 Java 反应式流驱动程序来学习如何指定查询。

重要

项目反应器库

本指南使用项目反应器库来消费发布者 实例,这些实例由 Java 反应式流驱动程序方法返回。要了解有关项目反应器库的更多信息以及如何使用它,请参阅入门在反应器文档中。要了解有关本指南中如何使用项目反应器库方法的更多信息,请参阅将数据写入 MongoDB 指南。

本指南使用Flux Publisher,它是来自Project Reactor库的Publisher实现。在Java响应式流中,您必须使用Publisher实现来控制应用程序中的数据传输方式。有关Flux类的更多信息,请参阅Project Reactor文档中的Flux

您可以通过创建一个查询过滤器来精炼查询返回的文档集合。查询过滤器是一个表达式,它指定MongoDB在读取或写入操作中用于匹配文档的搜索条件。在查询过滤器中,您可以提示驱动程序搜索与您的查询完全匹配的文档,或者您可以组合查询过滤器以表达更复杂的匹配条件。

本指南中的示例在名为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() 比较运算符方法。

以下示例在 find() 方法中将 eq() 比较运算符方法指定为查询筛选器参数。该代码返回所有具有 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 服务器手册中的比较查询运算符指南。

以下示例在查询筛选器中将 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服务器手册中的逻辑查询运算符指南。

以下示例在一个查询过滤器中指定了or()逻辑运算符方法,作为find()方法的一个参数。该代码返回所有qty字段值大于5color字段值为"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服务器手册中的数组查询运算符指南。

以下示例在查询过滤器中指定了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服务器手册中的元素查询运算符指南。

以下示例在查询过滤器中指定了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(),在文档上执行文本搜索

  • regex(),返回与指定正则表达式匹配的文档

  • mod()函数执行对字段值的取模操作,并返回余数为指定值的文档

要查看评估运算符的完整列表,请参阅MongoDB服务器手册中的评估查询运算符指南。

以下示例在查询过滤器中指定了一个用于find()方法的参数的regex()评估运算符方法。该代码使用正则表达式返回所有具有至少两个连续的"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服务器手册中的查询文档指南。

要了解更多关于本指南中讨论的任何方法或类型,请参阅以下API文档

返回

读取数据