Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver
/

Read Operations

On this page

  • Prerequisites
  • Connect to a MongoDB Deployment
  • Query a Collection
  • Query Filters
  • Empty Filter
  • Filters Helper
  • FindPublisher
  • Projections
  • Sorts
  • Sort with Projections
  • Explain
  • Read Preference
  • Read Concern

Read operations retrieve documents or information about documents from a collection. You can specify a filter to retrieve only those documents that match the filter condition.

You must set up the following components to run the code examples in this guide:

  • A test.restaurants collection populated with documents from the restaurants.json file in the documentation assets GitHub.

  • The following import statements:

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.*;

Important

This guide uses the Subscriber implementations, which are described in the Quick Start Primer.

First, connect to a MongoDB deployment, then declare and define MongoDatabase and MongoCollection instances.

The following code connects to a standalone MongoDB deployment running on localhost on port 27017. Then, it defines the database variable to refer to the test database and the collection variable to refer to the restaurants collection:

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

To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.

To query the collection, you can use the collection's find() method.

You can call the method without any arguments to query all documents in a collection:

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

Or, you can pass a filter to query for documents that match the filter criteria:

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

To query for documents that match certain conditions, pass a filter document to the find() method.

To specify an empty filter and match all documents in a collection, use an empty Document object:

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

Tip

When using the find() method, you can also call the method without passing any filter object to match all documents in a collection.

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

To facilitate the creation of filter documents, the driver provides the Filters class that provides filter condition helper methods.

This example find operation includes a filter Document instance which specifies the following conditions:

  • stars field value is greater than or equal to 2 and less than 5

  • categories field equals "Bakery", or if categories is an array field, contains the string "Bakery" as an element

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

The following example specifies the same filter condition using the Filters helper methods:

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

To view a list of query filter operators, see Query and Projection Operators in the Server manual. To view a list of Filters helpers, see the Filters API documentation.

The find() method returns an instance of the FindPublisher interface. The interface provides various methods that you can chain to the find() method to modify the output or behavior of the query, such as sort() or projection(), as well as for iterating the results via the subscribe() method.

By default, queries in MongoDB return all fields in matching documents. To specify the fields to return in the matching documents, you can specify a projection document.

This find operation example includes a projection Document which specifies that the matching documents include only the name, stars, and the categories fields:

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());

To facilitate the creation of projection documents, the driver provides the Projections class.

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

In the projection document, you can also specify a projection expression by using a projection operator.

To view an example that uses the Projections.metaTextScore() method, see the Text Search tutorial.

To sort documents, pass a sort specification document to the FindPublisher.sort() method. The driver provides Sorts helper methods to facilitate the creation of the sort specification document.

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

The FindPublisher methods themselves return FindPublisher objects, and as such, you can append multiple FindPublisher methods to the find() method:

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());

To explain a find operation, call the FindPublisher.explain() method:

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

For read operations on replica sets or sharded clusters, you can configure the read preference at the following levels:

  • In a MongoClient in the following ways:

    • By creating a MongoClientSettings instance:

      MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
      .applyConnectionString(new ConnectionString("mongodb://host1,host2"))
      .readPreference(ReadPreference.secondary())
      .build());
    • By creating a ConnectionString instance:

      MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readPreference=secondary");
  • In a MongoDatabase by using the withReadPreference() method:

    MongoDatabase database = mongoClient.getDatabase("test")
    .withReadPreference(ReadPreference.secondary());
  • In a MongoCollection by using the withReadPreference() method:

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

MongoDatabase and MongoCollection instances are immutable. Calling withReadPreference() on an existing MongoDatabase or MongoCollection instance returns a new instance and does not affect the instance on which the method is called.

In the following example, the collectionWithReadPref instance has the read preference of primaryPreferred whereas the read preference of the collection is unaffected:

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

For read operations on replica sets or sharded clusters, applications can configure the read concern at the following levels:

  • In a MongoClient in the following ways:

    • By creating a MongoClientSettings instance:

      MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
      .applyConnectionString(new ConnectionString("mongodb://host1,host2"))
      .readConcern(ReadConcern.MAJORITY)
      .build());
    • By creating a ConnectionString instance:

      MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readConcernLevel=majority");
  • In a MongoDatabase by using the withReadConcern() method:

    MongoDatabase database = mongoClient.getDatabase("test")
    .withReadConcern(ReadConcern.MAJORITY);
  • In a MongoCollection by using the withReadConcern() method:

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

MongoDatabase and MongoCollection instances are immutable. Calling withReadConcern() on an existing MongoDatabase or MongoCollection instance returns a new instance and does not affect the instance on which the method is called.

In the following example, the collWithReadConcern instance has an AVAILABLE read concern whereas the read concern of the collection is unaffected:

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

You can build MongoClientSettings, MongoDatabase, or MongoCollection instances to include combinations of read concerns, read preferences, and write concerns.

For example, the following code sets all three at the collection level:

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

Back

Create Indexes