Skip to content
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
69 changes: 69 additions & 0 deletions source/includes/read/specify-documents-to-return.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package org.example
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Sorts
import com.mongodb.kotlin.client.MongoClient

// start-data-class
data class Restaurant(
val name: String,
val borough: 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-limit
val results = collection
.find(eq(Restaurant::cuisine.name, "Italian"))
.limit(5)

results.forEach { result ->
println(result)
}
// end-limit

// start-sort
val results = collection
.find(eq(Restaurant::cuisine.name, "Italian"))
.sort(Sorts.ascending(Restaurant::name.name))

results.forEach { result ->
println(result)
}
// end-sort

// start-skip
val results = collection
.find(eq(Restaurant::cuisine.name, "Italian"))
.skip(10)

results.forEach { result ->
println(result)
}
// end-skip

// start-limit-sort-skip
val results = collection
.find(eq(Restaurant::cuisine.name, "Italian"))
.sort(Sorts.ascending(Restaurant::name.name))
.skip(10)
.limit(5)

results.forEach { result ->
println(result)
}
// end-limit-sort-skip
}
3 changes: 2 additions & 1 deletion source/read.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ Read Data from MongoDB
:maxdepth: 1

/read/retrieve
/read/count
/read/project
/read/specify-documents-to-return
/read/count

Overview
--------
Expand Down
198 changes: 198 additions & 0 deletions source/read/specify-documents-to-return.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
.. _kotlin-sync-specify-documents-to-return:

===========================
Specify Documents to Return
===========================

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

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

.. meta::
:keywords: read, paginate, pagination, order, code example

Overview
--------

In this guide, you can learn how to specify which documents to return from a read
operation by using the following methods:

- ``limit()``: Specifies the maximum number of documents to return from a query
- ``sort()``: Specifies the sort order for the returned documents
- ``skip()``: Specifies the number of documents to skip before returning query results

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/specify-documents-to-return.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:

.. _kotlin-sync-limit:

Limit
-----

To specify the maximum number of documents returned from a read operation,
call the ``limit()`` method.

The following example finds all restaurants that have a ``cuisine`` field value
of ``"Italian"`` and limits the results to 5 documents:

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

.. input:: /includes/read/specify-documents-to-return.kt
:start-after: start-limit
:end-before: end-limit
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(name=Philadelphia Grille Express, borough=Brooklyn, cuisine=Italian)
Restaurant(name=Isle Of Capri Resturant, borough=Manhattan, cuisine=Italian)
Restaurant(name=Marchis Restaurant, borough=Manhattan, cuisine=Italian)
Restaurant(name=Crystal Room, borough=Staten Island, cuisine=Italian)
Restaurant(name=Forlinis Restaurant, borough=Manhattan, cuisine=Italian)

.. tip::

The preceding example returns the first five documents returned by the query in
:manual:`natural order </reference/glossary/#std-term-natural-order>`. The following
section describes how to return the documents in a specified sort order.

.. _kotlin-sync-sort:

Sort
----

To return documents in a specified order, call the ``sort()`` method. The ``sort()``
method takes a sort direction as a parameter. To specify the sort direction,
use the ``Sorts.ascending()`` or ``Sorts.descending()`` method. The ``Sorts.ascending()``
method sorts values from lowest to highest, and the ``Sorts.descending()`` method sorts
values from highest to lowest. If you don't specify a sort direction, ``sort()`` returns
the documents in ascending order.

The following example returns all documents with a ``cuisine`` field value of
``"Italian"``, sorted by the value of the ``name`` field in ascending order:

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

.. input:: /includes/read/specify-documents-to-return.kt
:start-after: start-sort
:end-before: end-sort
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(name=(Lewis Drug Store) Locanda Vini E Olii, borough=Brooklyn, cuisine=Italian)
Restaurant(name=101 Restaurant And Bar, borough=Brooklyn, cuisine=Italian)
Restaurant(name=44 Sw Ristorante & Bar, borough=Manhattan, cuisine=Italian)
Restaurant(name=900 Park, borough=Bronx, cuisine=Italian)
Restaurant(name=A Voce, borough=Manhattan, cuisine=Italian)
...

.. _kotlin-sync-skip:

Skip
----

To skip a specified number of documents before returning your query results,
call the ``skip()`` method and pass in the number of documents to skip. The
``skip()`` method ignores the specified number of documents in your query
results and returns the rest.

The following example returns all documents that have a ``cuisine`` field value
of ``"Italian"`` and skips the first 10 documents:

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

.. input:: /includes/read/specify-documents-to-return.kt
:start-after: start-skip
:end-before: end-skip
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(name=San Pietro, borough=Manhattan, cuisine=Italian)
Restaurant(name=Manetta's Ristorante, borough=Queens, cuisine=Italian)
Restaurant(name=Salvi Restaurant, borough=Brooklyn, cuisine=Italian)
Restaurant(name=Tommaso Restaurant, borough=Brooklyn, cuisine=Italian)
Restaurant(name=Da Rosina Restaurant, borough=Manhattan, cuisine=Italian)
...

Combine Limit, Sort, and Skip
-----------------------------

You can combine the ``limit()``, ``sort()``, and ``skip()`` methods in a single
operation. This allows you to set a maximum number of sorted documents to
return, skipping a specified number of documents before returning.

The following example returns documents with the ``cuisine`` field value of
``"Italian"``. The results are sorted in alphabetical order, skipping the first
10 documents and limiting the results to 5 documents:

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

.. input:: /includes/read/specify-documents-to-return.kt
:start-after: start-limit-sort-skip
:end-before: end-limit-sort-skip
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(name=Acqua, borough=Manhattan, cuisine=Italian)
Restaurant(name=Acqua Restaurant, borough=Manhattan, cuisine=Italian)
Restaurant(name=Acqua Santa, borough=Brooklyn, cuisine=Italian)
Restaurant(name=Acquista Trattoria, borough=Queens, cuisine=Italian)
Restaurant(name=Acquolina Catering, borough=Manhattan, cuisine=Italian)

.. note::

The order in which you call these methods doesn't change the documents
that are returned. The driver automatically reorders the calls to perform the
sort and skip operations first, and the limit operation afterward.

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

.. TODO: For more information about specifying a query, see :ref:`kotlin-sync-specify-query`.

For more information about retrieving documents, see :ref:`kotlin-sync-retrieve`.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Note for reviewers: The retrieve page here is currently also in review. This PR should be merged in after the retrieve page is merged.

Link to Retrieve page PR


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>`__
- `limit() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/limit.html>`__
- `sort() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/sort.html>`__
- `skip() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/skip.html>`__