Overview
In this guide, you can learn how to use the Kotlin Sync driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.
Sample Data
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 the
Get Started with Atlas guide. To learn more about
aggregation operations and builders, see the Aggregation Operations guide.
Run a MongoDB Search Query
This section shows how to create an aggregation pipeline to run a
MongoDB Search query on a collection. You can use the Aggregates.search() builder
method to create a $search pipeline stage, which specifies the search
criteria. Then, call the aggregate() method and pass your pipeline as a
parameter.
Note
Only Available on Atlas for MongoDB v4.2 and later
This aggregation pipeline operator is only available for collections hosted on MongoDB Atlas clusters running v4.2 or later that are covered by a MongoDB Search index. Learn more about the required setup and the functionality of this operator from the MongoDB Search documentation.
Before running a MongoDB Search query, you must create a MongoDB Search index on your collection. To learn how to programmatically create a MongoDB Search index, see the Create a Search Index section in the Indexes guide.
MongoDB Search Example
This example runs a MongoDB Search query by performing the following actions:
Constructs a
$searchstage by using theAggregates.search()builder method, instructing the driver to query for documents in which thetitlefield contains the word"Alabama"Constructs a
$projectstage by using theAggregates.project()builder method, instructing the driver to include thetitlefield in the query resultsPasses the pipeline stages to the
aggregate()method and prints the results
val pipeline: List<Bson> = listOf( search(SearchOperator.text( fieldPath("title"), "Alabama")), project(Projections.include("title")) ) val results = collection.aggregate(pipeline) results.forEach { doc -> println(doc.toJson()) }
{"_id": {"$oid": "..."}, "title": "Alabama Moon"} {"_id": {"$oid": "..."}, "title": "Crazy in Alabama"} {"_id": {"$oid": "..."}, "title": "Sweet Home Alabama"}
MongoDB Search Metadata
Use the searchMeta() method to create a $searchMeta pipeline stage, which returns
only the metadata from the Atlas full-text search results.
Tip
Only Available on Atlas for MongoDB v4.4.11 and later
This aggregation pipeline operator is available only on MongoDB Atlas clusters running v4.4.11 and later.
The following example shows the near metadata for a MongoDB Search
aggregation stage:
searchMeta( SearchOperator.near(2010, 1, fieldPath("year")) )
Create Pipeline Search Stages
The Kotlin Sync 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 | |
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 | |
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. |
Example Pipeline Search Stage
Note
Atlas Sample Dataset
This example uses the sample_mflix.movies collection from the Atlas sample
datasets. To learn how to set up a free-tier Atlas cluster and load the
sample dataset, see the Get Started with Atlas tutorial
in the Atlas documentation.
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 Create a Search Index section of the Indexes guide.
The following code creates a $search stage that has the following
specifications:
Checks that the
genresarray includes"Comedy"Searches the
fullplotfield for the phrase"new york"Matches
yearvalues between1950and2000, inclusiveSearches for
titlevalues that begins with the term"Love"
val searchStage = Aggregates.search( SearchOperator.compound() .filter( listOf( SearchOperator.`in`(fieldPath("genres"), listOf("Comedy")), SearchOperator.phrase(fieldPath("fullplot"), "new york"), SearchOperator.numberRange(fieldPath("year")).gtLt(1950, 2000), SearchOperator.wildcard(fieldPath("title"), "Love *") ) ) ) val projectStage = Aggregates.project( Projections.include("title", "year", "genres")) val pipeline = listOf(searchStage, projectStage) val results = collection.aggregate(pipeline) results.forEach { result -> println(result) }
{"_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.
Additional Information
To learn more about MongoDB Search, see MongoDB Search in the Atlas documentation.
API Documentation
To learn more about the methods mentioned in this guide, see the following API documentation: