mongo-Java-Driver/4.1/../) : Driver/blob/master/docs/reference/content/driver/tutorials/perform-Read-Operations - MD

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

 (/mongo-java-driver/4.1/..

/) 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:

Consumer<Document> printConsumer = new Consumer<Document>() {


@Override
public void accept(final Document document) {
System.out.println(document.toJson());
}
};
Connect to a MongoDB Deployment
 (/mongo-java-driver/4.1/../) Search docs 

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:

MongoClient mongoClient = MongoClients.create();


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

For additional information on connecting to MongoDB, see Connect to MongoDB (/mongo-java-


driver/4.1/driver/tutorials/connect-to-mongodb/).

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:

collection.find(eq("name", "456 Cookies Shop"))


.forEach(printConsumer);

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:

For the find() (/mongo-java-driver/4.1/apidocs/mongodb-driver-


sync/com/mongodb/client/MongoCollection.html#find()) method, you can also call the method
without passing a filter object to match all documents in a collection.

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:

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


.forEach(printConsumer);
For a list of MongoDB query filter operators, refer to the MongoDB Manual
 (/mongo-java-driver/4.1/../)
(http://docs.mongodb.org/manual/reference/operator/query
Search docs
). For the associated Filters helpers, see

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.

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))
.forEach(printConsumer);

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/ )

For an example on using the Projections.metaTextScore (/mongo-java-driver/4.1/apidocs/mongodb-


driver-core/com/mongodb/client/model/Projections.html#metaTextScore(java.lang.String) ), see the Text
Search tutorial (/mongo-java-driver/4.1/driver/tutorials/text-search/).

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.

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


.sort(Sorts.ascending("name"))
.forEach(printConsumer);

Sort with Projections


The FindIterable (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/FindIterable.html ) methods themselves return FindIterable objects, and as
such, you can append multiple FindIterable 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()))
.forEach(printConsumer);

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 ):

MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()


.applyConnectionString(new ConnectionString("mon
.readPreference(ReadPreference.secondary())
.build());

Via ConnectionString (/mongo-java-driver/4.1/apidocs/mongodb-driver-


core/com/mongodb/ConnectionString.html ), as in the following example:

MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readPreferen

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 

MongoDatabase database = mongoClient.getDatabase("test")


.withReadPreference(ReadPreference.secondary());

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:

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.

For example, in the following, the collectionWithReadPref instance has the read preference of
primaryPreferred whereas the read preference of the collection is unaffected.

MongoCollection<Document> collectionWithReadPref = collection.withReadPreference(ReadPreference.prim

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

Via ConnectionString (/mongo-java-driver/4.1/apidocs/mongodb-driver-


core/com/mongodb/ConnectionString.html ), as in the following example:

MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readConcernL

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:

MongoDatabase database = mongoClient.getDatabase("test")


.withReadConcern(ReadConcern.MAJORITY);

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:

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.

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

You can build MongoClientSettings , MongoDatabase , or MongoCollection to include a combination of


read concern, read preference, and write concern (http://docs.mongodb.org/manual/reference/write-
concern ).

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

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

 Create Indexes (/mongo-java-driver/4.1/driver/tutorials/indexes/)


Client Side Encryption  (/mongo-java-driver/4.1/driver/tutorials/client-side-encryption/)

You might also like