For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Run MongoDB Search Queries

In this guide, you can learn how to use the Scala driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on your collections. MongoDB Search indexes specify the behavior of the search and the fields to index.

To learn how to create and manage MongoDB Search indexes by using the Scala driver, see the MongoDB Search and MongoDB Vector Search Indexes guide.

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started with Atlas.

Note

MongoDB Search is available on the following deployments:

  • MongoDB Atlas v4.2 or later

  • MongoDB Community Edition v8.2 or later

Your collection must have a MongoDB Search index to run MongoDB Search queries. To learn how to create a MongoDB Search index, see the MongoDB Search and MongoDB Vector Search Indexes guide.

To perform a full-text search, call the aggregate() method with a $search pipeline stage. The Scala driver provides the Aggregates.search() helper method to create this stage. The search() method requires the following arguments:

  • SearchOperator instance that specifies the field and text to search for

  • SearchOptions instance that specifies options to customize the search, including the name of the MongoDB Search index to use

The following example searches the title field for the text "Alabama" and projects only the _id field, which is included by default, and the title field of matching documents:

val operator = SearchOperator.text(
SearchPath.fieldPath("title"), "Alabama")
val options = searchOptions().index("<search index name>")
val pipeline = Seq(
Aggregates.search(operator, options),
Aggregates.project(Projections.include("title"))
)
try {
Await
.result(collection.aggregate(pipeline).toFuture(), 20.seconds)
.foreach((doc: Document) => println(doc.toJson()))
} catch {
case e: Throwable => println(s"There was an error: $e")
}
{"_id": {"$oid": "..."}, "title": "Alabama Moon"}
{"_id": {"$oid": "..."}, "title": "Crazy in Alabama"}
{"_id": {"$oid": "..."}, "title": "Sweet Home Alabama"}

Tip

To view MongoDB Search tutorials in the Atlas documentation, see Run Atlas Search Queries.

Note

MongoDB Search metadata is available on the following deployments:

  • MongoDB Atlas v4.4.11 or later

  • MongoDB Community Edition v8.2 or later

Use the Aggregates.searchMeta() helper method to retrieve only the metadata from a MongoDB Search query without returning the search results. The following example returns metadata for a query that searches the year field for values near 2010:

try {
Await
.result(
collection.aggregate(Seq(
Aggregates.searchMeta(
SearchOperator.near(2010, 1, SearchPath.fieldPath("year")))
)).toFuture(),
20.seconds
)
.foreach((doc: Document) => println(doc.toJson()))
} catch {
case e: Throwable => println(s"There was an error: $e")
}
{"count": {"lowerBound": 35}}

The Scala driver provides helper methods for the following operators:

Operator
Description

Performs a search for a word or phrase that contains a sequence of characters from an incomplete input string.

Combines two or more operators into a single query.

Checks whether a field matches a value you specify. Maps to the equals() and equalsNull() methods.

Tests if a path to a specified indexed field name exists in a document.

Performs a search for an array of BSON number, date, boolean, objectId, uuid, or string values at the given path and returns documents where the value of the field equals any value in the specified array.

Returns documents similar to input documents.

Supports querying and scoring numeric, date, and GeoJSON point values.

Performs a search for documents containing an ordered sequence of terms using the analyzer specified in the index configuration.

Supports querying a combination of indexed fields and values.

Supports querying and scoring numeric, date, and string values. Maps to the numberRange() and dateRange() methods.

Interprets the query field as a regular expression.

Performs a full-text search using the analyzer that you specify in the index configuration.

Enables queries which use special characters in the search string that can match any character.

Before you can run this example, you must create a MongoDB Search index on the movies collection that has the following definition:

{
"mappings": {
"dynamic": true,
"fields": {
"title": {
"analyzer": "lucene.keyword",
"type": "string"
},
"genres": {
"normalizer": "lowercase",
"type": "token"
}
}
}
}

To learn more about creating MongoDB Search indexes, see the MongoDB Search and MongoDB Vector Search Indexes guide.

The following code creates a $search stage that has the following specifications:

  • Checks that the genres array includes "Comedy"

  • Searches the fullplot field for the phrase "new york"

  • Matches year values between 1950 and 2000, inclusive

  • Searches for title values that begins with the term "Love"

val searchStage = Aggregates.search(
SearchOperator.compound()
.must(
Iterable(
SearchOperator.in(fieldPath("genres"), List("Comedy")),
SearchOperator.phrase(fieldPath("fullplot"), "new york"),
SearchOperator.numberRange(fieldPath("year")).gtLt(1950, 2000),
SearchOperator.wildcard("Love *", fieldPath("title")),
).asJava
)
)
val projectStage = Aggregates.project(
Projections.include("title", "year", "genres"))
try {
Await
.result(
collection.aggregate(Seq(searchStage, projectStage)).toFuture(),
20.seconds
)
.foreach((doc: Document) => println(doc.toJson()))
} catch {
case e: Throwable => println(s"There was an error: $e")
}
{"_id": ..., "genres": ["Comedy", "Romance"],
"title": "Love at First Bite", "year": 1979}
{"_id": ..., "genres": ["Comedy", "Drama"],
"title": "Love Affair", "year": 1994}

To learn more about the MongoDB Search helper methods, see the SearchOperator interface reference in the Driver Core API documentation.

For more information about MongoDB Search, see MongoDB Search Overview in the Atlas documentation.

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