Professional Documents
Culture Documents
mongo-Java-Driver/4.1/../) : Driver/blob/master/docs/reference/content/driver/tutorials/perform-Read-Operations - MD
mongo-Java-Driver/4.1/../) : Driver/blob/master/docs/reference/content/driver/tutorials/perform-Read-Operations - MD
mongo-Java-Driver/4.1/../) : Driver/blob/master/docs/reference/content/driver/tutorials/perform-Read-Operations - MD
/) Search docs
(https://github.com/mongodb/mongo-java-
driver/blob/master/docs/reference/content/driver/tutorials/perform-
read-operations.md)
Java Driver (/mongo-java-driver/4.1/driver/) Tutorials (/mongo-java-driver/4.1/driver/tutorials/) Read Operations
Find Operations
Find operations retrieve documents from a collection. You can specify a filter to select only those
documents that match the filter condition.
Prerequisites
The example below requires a restaurants collection in the test database. To create and populate
the collection, follow the directions in github (https://github.com/mongodb/docs-assets/tree/drivers).
Include the following import statements:
import com.mongodb.*;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Filters;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import com.mongodb.client.model.Sorts;
import java.util.Arrays;
import java.util.function.Consumer;
import org.bson.Document;
Include the following code which the examples in the tutorials will use to print the results of the find
operations:
Connect to a MongoDB deployment and declare and define a MongoDatabase instance and a
MongoCollection instance
For example, include the following code to connect to a standalone MongoDB deployment running on
localhost on port 27017 and define database to refer to the test database and collection to refer to
the restaurants collection:
Query a Collection
To query the collection, you can use the collection’s find() (/mongo-java-driver/4.1/apidocs/mongodb-
driver-sync/com/mongodb/client/MongoCollection.html#find() ) method.
You can call the method without any arguments to query all documents in a collection:
collection.find().forEach(printConsumer);
Or pass a filter to query for documents that match the filter criteria:
Query Filters
To query for documents that match certain conditions, pass a filter document to the find() (/mongo-
java-driver/4.1/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#find() ) method.
Empty Filter
To specify an empty filter (i.e. match all documents in a collection), use an empty Document (/mongo-
(/mongo-java-driver/4.1/../)
java-driver/4.1/apidocs/bson/org/bson/Document.html ) object.
Search docs
collection.find(new Document()).forEach(printConsumer);
TIP:
collection.find().forEach(printConsumer);
Filters Helper
To facilitate the creation of filter documents, the Java driver provides the Filters (/mongo-java-
driver/4.1/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html ) class that provides filter
condition helper methods.
Consider the following find operation which includes a filter Document which specifies that:
the stars field is greater than or equal to 2 and less than 5, AND
the categories field equals "Bakery" (or if categories is an array, contains the string "Bakery"
as an element):
collection.find(
new Document("stars", new Document("$gte", 2)
.append("$lt", 5))
.append("categories", "Bakery")).forEach(printConsumer);
The following example specifies the same filter condition using the Filters (/mongo-java-
driver/4.1/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html ) helper methods:
Filters (/mongo-java-driver/4.1/apidocs/mongodb-driver-core/com/mongodb/client/model/Filters.html ).
See also the Query Documents Tutorial (http://docs.mongodb.org/manual/tutorial/query-documents ) for
an overview of querying in MongoDB, including specifying filter conditions on arrays and embedded
documents.
FindIterable
The find() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#find() ) method returns an instance of the
FindIterable (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/FindIterable.html ) 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()
(/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/FindIterable.html#sort(org.bson.conversions.Bson) ) or projection()
(/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/FindIterable.html#projection(org.bson.conversions.Bson) ), as well as for
iterating the results, such as iterator() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoIterable.html#iterator() ).
Projections
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
(http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/#projection-document ).
Consider the following find operation which includes a projection Document which specifies that the
matching documents return only the name field, stars field, and the categories field.
To facilitate the creation of projection documents, the Java driver provides the Projections (/mongo-
java-driver/4.1/apidocs/mongodb-driver-core/com/mongodb/client/model/Projections.html ) class.
(/mongo-java-driver/4.1/../)
collection.find(and(gte("stars", Search docs
2), lt("stars", 5), eq("categories", "Bakery")))
.projection(fields(include("name", "stars", "categories"), excludeId()))
.forEach(printConsumer);
In the projection document, you can also specify a projection expression using a projection operator
(http://docs.mongodb.org/manual/reference/operator/projection/ )
Sorts
To sort documents, pass a sort specification document
(http://docs.mongodb.org/manual/reference/method/cursor.sort/#cursor.sort ) to the
FindIterable.sort() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/FindIterable.html#sort(org.bson.conversions.Bson) ) method. The Java driver
provides Sorts (/mongo-java-driver/4.1/builders/sorts/) helpers to facilitate the sort specification
document.
MongoIterable
The MongoIterable (/mongo-java-driver/4.1/apidocs/mongodb-driver-
(/mongo-java-driver/4.1/../) Search docs
sync/com/mongodb/client/MongoIterable.html ) interface provides helper methods to access the results
of an operation:
iterator() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoIterable.html#iterator() )
first() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoIterable.html#first() )
map() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoIterable.html#map(com.mongodb.Function) )
into() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoIterable.html#into(A) )
Read Preference
For read operations on replica sets (http://docs.mongodb.org/manual/replication/ ) or sharded clusters
(http://docs.mongodb.org/manual/sharding/ ), applications can configure the read preference
(http://docs.mongodb.org/manual/reference/read-preference ) at three levels:
In a MongoClient() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoClient.html )
Via MongoClientSettings (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/MongoClientSettings.html ):
In a MongoDatabase (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoDatabase.html ) via its withReadPreference (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoDatabase.html#withReadPreference(com.mongodb.ReadPreferen
) method. (/mongo-java-driver/4.1/../) Search docs
In a MongoCollection (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html ) via its withReadPreference (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#withReadPreference(com.mongodb.ReadPreferen
) method:
For example, in the following, the collectionWithReadPref instance has the read preference of
primaryPreferred whereas the read preference of the collection is unaffected.
Read Concern
For read operations on replica sets (http://docs.mongodb.org/manual/replication/ ) or sharded clusters
(http://docs.mongodb.org/manual/sharding/ ), applications can configure the read concern
(http://docs.mongodb.org/manual/reference/read-concern ) at three levels:
In a MongoClient() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoClient.html )
Via MongoClientSettings (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/MongoClientSettings.html ):
(/mongo-java-driver/4.1/../) Search docs
MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mon
.readConcern(ReadConcern.MAJORITY)
.build());
In a MongoDatabase (/mongo-java-driver/4.1/apidocs/mongodb-driver-
reactivestreams/com/mongodb/reactivestreams/client/MongoDatabase.html ) via its
withReadConcern (/mongo-java-driver/4.1/apidocs/mongodb-driver-
reactivestreams/com/mongodb/reactivestreams/client/MongoDatabase.html#withReadConcern(com
) method, as in the following example:
In a MongoCollection (/mongo-java-driver/4.1/apidocs/mongodb-driver-
reactivestreams/com/mongodb/reactivestreams/client/MongoCollection.html ) via its
withReadConcern (/mongo-java-driver/4.1/apidocs/mongodb-driver-
reactivestreams/com/mongodb/reactivestreams/client/MongoCollection.html#withReadConcern(com
) method, as in the following example:
For example, in the following, the collWithReadConcern instance has an AVAILABLE read concern
whereas the read concern of the collection is unaffected.
(/mongo-java-driver/4.1/../)
MongoCollection<Document> Search docs
collWithReadConcern = collection.withReadConcern(ReadConcern.AVAILABLE);
For example, the following sets all three at the collection level:
collection = database.getCollection("restaurants")
.withReadPreference(ReadPreference.primary())
.withReadConcern(ReadConcern.MAJORITY)
.withWriteConcern(WriteConcern.MAJORITY);