Docs Menu
Docs Home
/ / /
Scala
/

Specify a Query

On this page

  • Overview
  • Sample Data
  • Exact Match
  • Comparison Operators
  • Logical Operators
  • Array Operators
  • Element Operators
  • Evaluation Operators
  • Additional Information
  • API Documentation

In this guide, you can learn how to specify a query by using the Scala driver.

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 that MongoDB uses to match documents in a read or write operation.

You can use query operators to express more complex matching criteria in a query filter. The Scala driver includes a Filters class that provides helper methods for applying query operators.

Tip

To view a full list of Filters helper methods, see the Filters API documentation.

The examples in this guide run operations on the fruits collection, which contains documents representing fruits. The following code example shows how to create a database and collection, then insert the sample documents into your collection:

val uri: String = "<connection string>"
val client: MongoClient = MongoClient(uri)
val database: MongoDatabase = client.getDatabase("db")
val collection: MongoCollection[Document] = database.getCollection("fruits")
// Inserts documents representing fruits
val fruits: Seq[Document] = Seq(
Document("_id" -> 1, "name" -> "apples", "qty" -> 5, "rating" -> 3, "color" -> "red", "type" -> Seq("fuji", "honeycrisp")),
Document("_id" -> 2, "name" -> "bananas", "qty" -> 7, "rating" -> 4, "color" -> "yellow", "type" -> Seq("cavendish")),
Document("_id" -> 3, "name" -> "oranges", "qty" -> 6, "rating" -> 2, "type" -> Seq("naval", "mandarin")),
Document("_id" -> 4, "name" -> "pineapples", "qty" -> 3, "rating" -> 5, "color" -> "yellow")
)
val result = collection.insertMany(fruits)
.subscribe((result: InsertManyResult) => println(result))

Literal value queries return documents that have an exact match to your query filter.

The following example specifies a query filter as a parameter to the find() method. The code returns all documents in which the value of the color field is "yellow":

val filter = equal("color", "yellow")
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"]}
{"_id": 4, "name": "pineapples", "qty": 3, "rating": 5, "color": "yellow"}

Note

Find All Documents

To find all documents in a collection, call the find() method without passing any parameters:

collection.find()

Comparison operators evaluate a document field value against a specified value in your query filter. The following list defines common comparison operators and their corresponding Filters helper methods:

Query Operator
Helper Method
Description

$gt

gt()

Matches documents in which the value of the given field is greater than the specified value.

$lte

lte()

Matches documents in which the value of the given field is less than or equal to the specified value.

$ne

ne()

Matches documents in which the value of the given field does not equal the specified value.

Tip

To view a full list of comparison operators, see the Comparison Query Operators guide in the MongoDB Server manual.

The following example passes a query filter to the find() method and uses the gt() method to apply the $gt comparison operator. The code returns all documents in which the value of the rating field is greater than 2:

val filter = gt("rating", 2)
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_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": "pineapples", "qty": 3, "rating": 5, "color": "yellow"}

Logical operators match documents by using logic applied to the results of two or more sets of expressions. The following table describes each logical operator and its corresponding Filters helper method:

Query Operator
Helper Method
Description

$and

and()

Matches documents that satisfy the conditions of all clauses

$or

or()

Matches documents that satisfy the conditions of one clause

$nor

nor()

Matches documents that do not satisfy the conditions of any clause

$not

not()

Matches documents that do not match the expression

Tip

To learn more about logical operators, see the Logical Query Operators guide in the MongoDB Server manual.

The following example passes a query filter to the find() method and uses the or() method to apply the $or logical operator. The code returns all documents in which the qty field value is greater than 5 or the color field value is "yellow":

val filter = or(gt("qty", 5), equal("color", "yellow"))
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_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": "pineapples", "qty": 3, "rating": 5, "color": "yellow"}

Array operators match documents based on the value or quantity of elements in an array field. The following table describes each array operator and its corresponding Filters helper method:

Query Operator
Helper Method
Description

$all

all()

Matches documents that have arrays containing all elements in the query

$elemMatch

elemMatch()

Matches documents if an element in their array field satisfies all conditions in the query

$size

size()

Matches documents that have arrays of a specified size

Tip

To learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.

The following example passes a query filter to the find() method and uses the size() method to apply the $size array operator. The code returns all documents in which the type array field contains 2 elements:

val filter = size("type", 2)
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_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 query data based on the presence or type of a field. The following table describes each element operator and its corresponding Filters helper method:

Query Operator
Helper Method
Description

$exists

exists()

Matches documents that have the specified field

$type

type()

Matches documents if a field has the specified type

Tip

To learn more about element operators, see the Element Query Operators guide in the MongoDB Server manual.

The following example passes a query filter to the find() method and uses the exists() method to apply the $exists element operator. The code returns all documents that have a color field:

val filter = exists("color")
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_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": "pineapples", "qty": 3, "rating": 5, "color": "yellow"}

Evaluation operators return data based on evaluations of either individual fields or the entire collection's documents. The following table describes common element operators and their corresponding Filters helper methods:

Query Operator
Helper Method
Description

$text

text()

Performs a text search on documents

$regex

regex()

Matches documents that have values satisfying a specified regular expression

$mod

mod()

Performs a modulo operation on the value of a field and matches documents with a specified result

Tip

To view a full list of evaluation operators, see the Evaluation Query Operators guide in the MongoDB Server manual.

The following example passes a query filter to the find() method and uses the regex() method to apply the $regex evaluation operator. The code uses a regular expression to return all documents in which the name field value has at least two consecutive 'p' characters:

val filter = regex("name", "p{2,}")
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"]}
{"_id": 4, "name": "pineapples", "qty": 3, "rating": 5, "color": "yellow"}

To learn more about querying documents, see the Query Documents guide in the MongoDB Server manual.

To learn more about retrieving documents with the Scala driver, see the Retrieve Data guide.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

  • find()

  • Filters

  • insertMany()

Back

Retrieve Data