Skip to content

DOCSP-51348-atlas-search-page #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 153 additions & 1 deletion source/atlas-search.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,156 @@

=========================
Run an Atlas Search Query
=========================
=========================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: full text, text analyzer, meta, pipeline, scoring, Lucene
:description: Learn about how to use Atlas Search in the {+driver-long+}.

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to
run :atlas:`Atlas Search </atlas-search/>` queries on a collection.
Atlas Search enables you to perform full-text searches on collections
hosted on MongoDB Atlas. Atlas 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:`Atlas sample datasets </sample-data>`. To learn how to
create a free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide. To learn more about
aggregation operations and builders, see the :ref:`kotlin-sync-aggregation` guide.

Run an Atlas Search Query
-------------------------

This section shows how to create an aggregation pipeline to run an
Atlas 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 :atlas:`MongoDB Atlas </>` clusters running v4.2 or later that are
covered by an :atlas:`Atlas Search index </reference/atlas-search/index-definitions/>`.
Learn more about the required setup and the functionality of this operator
from the :atlas:`Atlas Search </atlas-search/>` documentation.

Before running an Atlas Search query, you must create an Atlas Search index
on your collection. To learn how to programmatically create an Atlas Search
index, see the :ref:`kotlin-sync-atlas-search-index-create` section in the Indexes guide.

Atlas Search Example
~~~~~~~~~~~~~~~~~~~~

This example runs an Atlas Search query by performing the
following actions:

- Constructs a ``$search`` stage by using the ``Aggregates.search()`` builder method,
instructing the driver to query for documents in which the ``title``
field contains the word ``"Alabama"``

- Constructs a ``$project`` stage by using the ``Aggregates.project()`` builder method,
instructing the driver to include the ``title`` field in the query results

- Passes the pipeline stages to the ``aggregate()`` method and prints the results

.. io-code-block::
:copyable:

.. input:: /includes/atlas-search.kt
:start-after: begin-atlas-search
:end-before: end-atlas-search
:language: kotlin
:dedent:

.. output::
:language: console
:visible: false

{"_id": {"$oid": "..."}, "title": "Alabama Moon"}
{"_id": {"$oid": "..."}, "title": "Crazy in Alabama"}
{"_id": {"$oid": "..."}, "title": "Sweet Home Alabama"}

Atlas Search Metadata
---------------------

Use the ``searchMeta()`` method to create a :manual:`$searchMeta
</reference/operator/aggregation/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 :atlas:`MongoDB Atlas </>` clusters running v4.4.11 and later.

The following example shows the ``near`` metadata for an Atlas Search
aggregation stage:

.. literalinclude:: /includes/aggregation/search-meta-agg.kt
:start-after: // begin atlasSearchMeta
:end-before: // end atlasSearchMeta
:language: kotlin
:dedent:

.. _kotlin-atlas-search-helpers:

Create Pipeline Search Stages
-----------------------------

.. sharedinclude:: dbx/jvm/atlas-search-operator-helpers.rst

.. replacement:: as-idx-link

the :ref:`kotlin-sync-atlas-search-index-create` section of the Indexes guide

.. replacement:: atlas-query-operators-example

.. io-code-block::

.. input:: /includes/aggregation/aggregation.kt
:language: kotlin
:start-after: // start-atlas-searchoperator-helpers
:end-before: // end-atlas-searchoperator-helpers
:dedent:

.. output::
:language: console
:visible: false

{"_id": ..., "genres": ["Comedy", "Romance"], "title": "Love at First Bite", "year": 1979}
{"_id": ..., "genres": ["Comedy", "Drama"], "title": "Love Affair", "year": 1994}

Additional Information
----------------------

To learn more about Atlas Search, see :atlas:`Atlas Search </atlas-search/>`
in the Atlas documentation.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about the methods mentioned in this guide, see
the following API documentation:

- `aggregate() <{+driver-api+}/-mongo-collection/aggregate.html>`__
- `Aggregates.search() <{+core-api+}/client/model/Aggregates.html#search(com.mongodb.client.model.search.SearchCollector)>`__
- `Aggregates.searchMeta() <{+core-api+}/client/model/Aggregates.html#searchMeta(com.mongodb.client.model.search.SearchCollector)>`__
- `Aggregates.project() <{+core-api+}/client/model/Aggregates.html#project(org.bson.conversions.Bson)>`__
- `SearchOperator <{+core-api+}/client/model/search/SearchOperator.html>`__
42 changes: 42 additions & 0 deletions source/includes/aggregation/search-meta-agg.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.example

import com.mongodb.ConnectionString
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.MongoClientSettings
import com.mongodb.client.model.Aggregates.searchMeta
import com.mongodb.client.model.search.SearchOperator
import com.mongodb.client.model.search.SearchPath.fieldPath
import com.mongodb.kotlin.client.MongoCollection
import org.bson.Document

fun runAtlasTextSearchMeta(collection: MongoCollection<Document>) {
val textSearchMeta =
// begin atlasSearchMeta
searchMeta(
SearchOperator.near(2010, 1, fieldPath("year"))
)
// end atlasSearchMeta

val aggregateStages = listOf(textSearchMeta)
println("aggregateStages: $aggregateStages")

collection.aggregate(aggregateStages).forEach { result ->
println(result)
}
}

fun main() {
val uri = "<connection string>"

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.retryWrites(true)
.build()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems it will align better with existing pattern to connection uri placeholder in code directly without indirection of a constant field:

val uri = "<connection string>"

val settings = MongoClientSettings.builder()
        .applyConnectionString(ConnectionString(uri))
        .retryWrites(true)
        .build()


MongoClient.create(settings).use { mongoClient ->
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")

runAtlasTextSearchMeta(collection)
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need the above comment? For one thing, it is not methods to be uncommented for the statement below is a method invocation, not the method declaration per se; so Uncomment the below statement is better?

But given we have provided this method as example, I think simply using it directly makes more sense:

runAtlasTextSearchMeta(collection)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, this is a remnant of old code where there were multiple methods that could be tested 😅 good catch!

}
41 changes: 41 additions & 0 deletions source/includes/atlas-search.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Runs an Atlas Search query by using the Kotlin sync driver

package org.example

import com.mongodb.ConnectionString
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.MongoClientSettings
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Aggregates.search
import com.mongodb.client.model.Projections
import com.mongodb.client.model.search.SearchOperator
import com.mongodb.client.model.search.SearchPath.fieldPath
import org.bson.Document
import org.bson.conversions.Bson

fun main() {
val uri = "<connection string>"

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.retryWrites(true)
.build()

val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")

// begin-atlas-search
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())
}
// end-atlas-search
}
Loading