Skip to content
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

DOCSP-41134: Retrieve Data #6

Merged
merged 11 commits into from
Jul 18, 2024
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
46 changes: 46 additions & 0 deletions source/includes/read/retrieve.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.kotlin.client.*
import com.mongodb.client.model.Filters.*

// start-data-class
data class Restaurant(
val name: String,
val cuisine: String
)
// end-data-class

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

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

val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")

// start-find
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
// end-find

// start-find-iterate
val results = collection.find(eq(Restaurant::cuisine.name, "Spanish"))
results.forEach { result ->
println(result)
}
// end-find-iterate

// start-find-all
val results = collection.find()
// end-find-all

// start-modified-find
val results = collection
.find(eq(Restaurant::cuisine.name, "Spanish"))
.limit(10)
.maxTime(10000)
// end-modified-find
}
3 changes: 2 additions & 1 deletion source/read.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Read Data from MongoDB
:titlesonly:
:maxdepth: 1

/read/retrieve
/read/count

Overview
Expand Down Expand Up @@ -67,7 +68,7 @@ given filter:
:copyable:
:dedent:

.. TODO: To learn more about the ``find()`` method, see the :ref:`kotlin-sync-retrieve-find` guide.
To learn more about the ``find()`` method, see the :ref:`kotlin-sync-retrieve-find` guide.

Count Documents in a Collection
-------------------------------
Expand Down
172 changes: 172 additions & 0 deletions source/read/retrieve.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
.. _kotlin-sync-retrieve:

=============
Retrieve Data
=============

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

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

.. meta::
:keywords: code examples, read, search, cursor

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to retrieve data from a
MongoDB collection by using read operations. You can call the ``find()`` method to
retrieve documents that match a set of criteria specified in a query filter.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
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.

The documents in this collection are modeled by the following {+language+} data class:

.. literalinclude:: /includes/read/retrieve.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:

.. _kotlin-sync-retrieve-find:

Find Documents
--------------

The ``find()`` method retrieves documents from a collection. This
method takes a **query filter** and returns all matching documents. A query filter is a
document that specifies the criteria that the driver uses to match documents from the
collection.

.. TODO: To learn more about query filters, see :ref:`kotlin-sync-specify-query`.

Find Documents Example
~~~~~~~~~~~~~~~~~~~~~~

The following example uses the ``find()`` method to find all documents in which the
value of the ``cuisine`` field is ``"Spanish"``:

.. literalinclude:: /includes/read/retrieve.kt
:start-after: start-find
:end-before: end-find
:language: kotlin
:copyable:
:dedent:

The ``find()`` operation in the preceding example returns a ``FindIterable`` object,
which you can iterate through by using the ``forEach()`` method, as shown in the following
example:

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

.. input:: /includes/read/retrieve.kt
:start-after: start-find-iterate
:end-before: end-find-iterate
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(name=Tropicoso Club, cuisine=Spanish)
Restaurant(name=Beso, cuisine=Spanish)
Restaurant(name=Sabor Latino Restaurant, cuisine=Spanish)
...

.. note:: Find All Documents

To find all documents in a collection, pass an empty filter to the ``find()`` method:

.. literalinclude:: /includes/read/retrieve.kt
:start-after: start-find-all
:end-before: end-find-all
:language: kotlin
:copyable:
:dedent:

Modify Find Behavior
~~~~~~~~~~~~~~~~~~~~

You can modify the behavior of the ``find()`` method by chaining methods to
the ``find()`` method call. The following table describes commonly used methods used for
modifying queries:

.. list-table::
:widths: 30 70
:header-rows: 1

* - Method
- Description

* - ``batchSize()``
- | Limits the number of documents to return per batch. To learn more about
batch size, see :manual:`cursor.batchSize() </reference/method/cursor.batchSize/>`
in the MongoDB Server manual.

* - ``collation()``
- | Sets the collation options for the query.

* - ``comment()``
- | Specifies a string to attach to the query. This can help you trace and interpret the
operation in the server logs and in profile data. To learn more about query comments,
see :manual:`$comment </reference/operator/query/comment/>` in the MongoDB Server
manual.

* - ``hint()``
- | Specifies the index to use for the query.

* - ``limit()``
- | Limits the number of documents to be returned from the query.

* - ``maxTime()``
- | Sets the maximum execution time on the server for this operation.

* - ``skip()``
- | Sets the number of documents to skip.

* - ``sort()``
- | Defines the sort criteria to apply to the query.

The following example chains the ``limit()`` and ``maxTime()`` methods to limit the
number of documents returned by the query to ``10`` and set a maximum execution time of
``10000`` milliseconds on the operation:

.. literalinclude:: /includes/read/retrieve.kt
:start-after: start-modified-find
:end-before: end-modified-find
:language: kotlin
:copyable:
:dedent:

For a full list of methods that modify the behavior of ``find()``, see the `API documentation <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/index.html>`__
for the ``FindIterable`` class.
rustagir marked this conversation as resolved.
Show resolved Hide resolved

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

.. TODO: To learn more about query filters, see :ref:`kotlin-sync-specify-query`.

To view runnable code examples that retrieve documents by using the {+driver-short+}, see
:ref:`kotlin-sync-read`.

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

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

- `find() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/find.html>`__
- `FindIterable <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/index.html>`__
Loading