Specify a Query
On this page
Overview
In this guide, you can learn how to specify a query by using the Java Reactive Streams driver.
Important
Project Reactor Library
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.
You can refine the set of documents that a query returns by creating a query filter. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. In a query filter, you can prompt the driver to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.
Sample Data
The examples in this guide run operations on a collection called
fruits
that contains the following documents:
{ "_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" },
The following code example shows how to create a database and collection, then insert the sample documents into your collection:
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(); } } }
Exact Match
Literal value queries return documents with an exact match to your query filter.
To return documents with an exact match, use the eq()
comparison operator method.
The following example specifies an eq()
comparison operator method as the
query filter parameter in the find()
method. The code returns all documents with a color
field value of "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'}
Tip
Find All Documents
To find all documents in a collection, call the find()
method without
specifying any parameters. The following example finds all documents in a
collection:
FindPublisher<Document> findDocPublisher = fruits.find(); Document findResults = Flux.from(findDocPublisher) .doOnNext(System.out::println) .blockLast();
Comparison Operators
Comparison operators evaluate a document field value against a specified value in your query filter. The following is a list of common comparison operator methods:
gt()
: Greater thanlte()
: Less than or Equalne()
: Not equal
To view a full list of comparison operators, see the Comparison Query Operators guide in the MongoDB Server manual.
The following example specifies a gt()
comparison operator method in a query filter as a
parameter to the find()
method. The code returns all documents with a
rating
field value greater than 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'}
Logical Operators
Logical operators match documents by using logic applied to the results of two or more sets of expressions. The following is a list of logical operator methods:
and()
, which returns all documents that match the conditions of all clausesor()
, which returns all documents that match the conditions of one clausenor()
, which returns all documents that do not match the conditions of any clausenot()
, which returns all documents that do not match the expression
To learn more about logical operators, see the Logical Query Operators guide in the MongoDB Server manual.
The following example specifies an or()
logical operator method in a query filter as a
parameter to the find()
method. The code returns all documents with a
qty
field value greater than 5
or a color
field value of
"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'}
Array Operators
Array operators match documents based on the value or quantity of elements in an array field. The following is a list of available array operator methods:
all()
, which returns documents with arrays that contain all elements in the queryelemMatch()
, which returns documents if an element in their array field matches all conditions in the querysize()
, which returns all documents with arrays of a specified size
To learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.
The following example specifies a size()
array operator method in a query filter as a
parameter to the find()
method. The code returns all documents with a
type
array field containing 2
elements.
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']}
Element Operators
Element operators query data based on the presence or type of a field. The following is a list of available element operator methods:
exists()
, which returns documents with the specified fieldtype()
, which returns documents if a field is of the specified type
To learn more about element operators, see the Element Query Operators guide in the MongoDB Server manual.
The following example specifies an exists()
element operator method in a query filter as a
parameter to the find()
method. The code returns all documents that have a
color
field.
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'}
Evaluation Operators
Evaluation operators return data based on evaluations of either individual fields or the entire collection's documents. The following is a list of common evaluation operator methods:
text()
, which performs a text search on the documentsregex()
, which returns documents that match a specified regular expressionmod()
, which performs a modulo operation on the value of a field and returns documents where the remainder is a specified value
To view a full list of evaluation operators, see the Evaluation Query Operators guide in the MongoDB Server manual.
The following example specifies a regex()
evaluation operator method in a query filter as a
parameter to the find()
method. The code uses a regular expression to return
all documents with a name
field value that has at least two consecutive
"p"
characters.
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'}
Additional Information
To learn more about querying documents, see the Query Documents guide in the MongoDB Server manual.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: