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.

  • Include the following import statements:

     import org.mongodb.scala._
     import org.mongodb.scala.model.Filters._
     import org.mongodb.scala.model.Projections._
     import org.mongodb.scala.model.Sorts._
    
important

This guide uses the Observable implicits as covered in the Quick Start Primer.

Connect to a MongoDB Deployment

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:

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("test")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

For additional information on connecting to MongoDB, see Connect to MongoDB.

Query a Collection

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().printResults()

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

collection.find(equal("name", "456 Cookies Shop"))
          .printResults()

Query Filters

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

Empty Filter

To specify an empty filter (i.e. match all documents in a collection), use an empty Document object.

collection.find(Document()).printResults()
tip

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

collection.find().printResults()

Filters Helper

To facilitate the creation of filter documents, the Scala driver provides the Filters 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(
     Document("stars" -> Document("$gte" -> 2, "$lt"-> 5, "categories" -> "Bakery")))
    .printResults()

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

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

For a list of MongoDB query filter operators, refer to the MongoDB Manual. For the associated Filters helpers, see Filters. See also the Query Documents Tutorial for an overview of querying in MongoDB, including specifying filter conditions on arrays and embedded documents.

FindObservable

The find() method returns an instance of the FindObservable class. The class 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.

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.

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), equal("categories", "Bakery")))
          .projection(Document("name" -> 1, "stars" -> 1, "categories" -> 1, "_id" -> 0))
          .printResults()

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

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
          .projection(fields(include("name", "stars", "categories"), excludeId()))
          .printResults()

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

For an example on using the Projections.metaTextScore, see the Text Search tutorial.

Sorts

To sort documents, pass a sort specification document to the FindObservable.sort() method. The Scala driver provides Sorts helpers to facilitate the sort specification document.

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
          .sort(ascending("name"))
          .printResults()

Sort with Projections

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

collection.find(and(gte("stars", 2), lt("stars", 5), equal("categories", "Bakery")))
          .sort(ascending("name"))
          .projection(fields(include("name", "stars", "categories"), excludeId()))
          .printResults()

Explain

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

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

The driver supports explain of find operations starting with MongoDB 3.0.

Read Preference

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

  • In a MongoClient()

      val mongoClient = MongoClient(MongoClientSettings.builder()
                                         .applyConnectionString(ConnectionString("mongodb://host1,host2"))
                                         .readPreference(ReadPreference.secondary())
                                         .build())
    
      val mongoClient = MongoClient("mongodb://host1:27017,host2:27017/?readPreference=secondary")
    
  • In a MongoDatabase via its withReadPreference method.

    val database = mongoClient.getDatabase("test")
                              .withReadPreference(ReadPreference.secondary())
    
  • In a MongoCollection via its withReadPreference method:

    val 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.

val collectionWithReadPref = collection.withReadPreference(ReadPreference.primaryPreferred())

Read Concern

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

  • In a MongoClient()

      val mongoClient = MongoClient(MongoClientSettings.builder()
                                     .applyConnectionString(ConnectionString("mongodb://host1,host2"))
                                     .readConcern(ReadConcern.MAJORITY)
                                     .build())
    
      val mongoClient = MongoClient("mongodb://host1:27017,host2:27017/?readConcernLevel=majority")
    
  • In a MongoDatabase via its withReadConcern method, as in the following example:

    val database = mongoClient.getDatabase("test")
                              .withReadConcern(ReadConcern.MAJORITY)
    
  • In a MongoCollection via its withReadConcern method, as in the following example:

    val 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.

val collWithReadConcern = collection.withReadConcern(ReadConcern.AVAILABLE)

You can build MongoClientSettings, MongoDatabase, or MongoCollection to include a combination of read concern, read preference, and write concern.

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

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