Skip to content

DOCSP-45196: Limit, skip, and sort #109

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
Dec 19, 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
51 changes: 51 additions & 0 deletions source/includes/read/limit-skip-sort.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
require 'bundler/inline'

gemfile do
source 'https://rubygems.org'
gem 'mongo'
end

uri = '<connection string>'

Mongo::Client.new(uri) do |client|
# Access the database and collection
# start-db-coll
database = client.use('sample_restaurants')
collection = database[:restaurants]
# end-db-coll

# Retrieves 5 documents that have a "cuisine" value of "Italian"
# start-limit
filter = { cuisine: 'Italian' }
collection.find(filter)
.limit(5)
.each { |doc| puts doc }
# end-limit

# Retrieves documents with a "cuisine" value of "Italian" and sorts in ascending "name" order
# start-sort
filter = { cuisine: 'Italian' }
collection.find(filter)
.sort(name: 1)
.each { |doc| puts doc }
# end-sort

# Retrieves documents with a "borough" value of "Manhattan" but skips the first 10 results
# start-skip
filter = { borough: 'Manhattan' }
collection.find(filter)
.skip(10)
.each { |doc| puts doc }
# end-skip

# Retrieves 5 documents with a "cuisine" value of "Italian", skips the first 10 results,
# and sorts by ascending "name" order
# start-limit-sort-skip
filter = { cuisine: 'Italian' }
collection.find(filter)
.limit(5)
.skip(10)
.sort(name: 1)
.each { |doc| puts doc }
# end-limit-sort-skip
end
3 changes: 2 additions & 1 deletion source/read.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ Read Data from MongoDB
:maxdepth: 1

Retrieve Data </read/retrieve>
Specify Fields to Return </read/project>
Specify Documents to Return </read/specify-documents-to-return>
Specify Fields to Return </read/project>
210 changes: 210 additions & 0 deletions source/read/specify-documents-to-return.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
.. _ruby-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 chaining the following methods to the ``find``
method:

- :ref:`limit <ruby-return-documents-limit>`: Specifies the maximum number of documents
to return from a query
- :ref:`sort <ruby-return-documents-sort>`: Specifies the sort order for the returned documents
- :ref:`skip <ruby-return-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 access this collection
from your {+language+} application, create a ``Mongo::Client`` object that connects to
an Atlas cluster and assign the following values to your ``database`` and ``collection``
variables:

.. literalinclude:: /includes/read/limit-skip-sort.rb
:language: ruby
:dedent:
:start-after: start-db-coll
:end-before: end-db-coll

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.

.. _ruby-return-documents-limit:

Limit
-----

To specify the maximum number of documents returned from a read operation, apply
the ``limit`` option to the operation. You can set this option by chaining the
``limit`` setter method to the ``find`` 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:

.. input:: /includes/read/limit-skip-sort.rb
:start-after: start-limit
:end-before: end-limit
:language: ruby
:dedent:

.. output::
:visible: false

{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Philadelhia Grille Express",
"restaurant_id"=>"40364305"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Isle Of Capri Restaurant",
"restaurant_id"=>"40364373"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Marchis Restaurant",
"restaurant_id"=>"40364668"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Crystal Room",
"restaurant_id"=>"40365013"}
{"_id"=>BSON::ObjectId('...'), ... , name"=>"Forlinis Restaurant",
"restaurant_id"=>"40365098"}

.. tip::

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

.. _ruby-return-documents-sort:

Sort
----

To return documents in a specified order, apply the ``sort`` option to
the read operation. You can set this option by chaining the ``sort``
setter method to the ``find`` method.

When calling ``sort``, pass the field to sort the results by and the
sort direction. A sort direction value of ``1`` sorts values from lowest
to highest, and a value of ``-1`` sorts them from highest to lowest.

The following example returns all documents that have a ``cuisine`` field value
of ``'Italian'``, sorted in ascending order of ``name`` field values:

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

.. input:: /includes/read/limit-skip-sort.rb
:start-after: start-sort
:end-before: end-sort
:language: ruby
:dedent:

.. output::
:visible: false

{"_id"=>BSON::ObjectId('...'), ... , "name"=>"(Lewis Drug Store) Locanda Vini E Olii",
"restaurant_id"=>"40804423"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"101 Restaurant And Bar",
"restaurant_id"=>"40560108"}
...
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Zucchero E Pomodori",
"restaurant_id"=>"41189590"}

.. _ruby-return-documents-skip:

Skip
----

To skip a specified number of documents before returning your query results, apply
the ``skip`` option to the read operation. You can set this option by chaining the
``skip`` setter method to the ``find`` method.

The following example returns all documents that have a ``borough`` field value
of ``'Manhattan'`` and skips the first ``10`` documents:

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

.. input:: /includes/read/limit-skip-sort.rb
:start-after: start-skip
:end-before: end-skip
:language: ruby
:dedent:

.. output::
:visible: false

{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Cafe Metro", "restaurant_id"=>"40363298"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Lexler Deli", "restaurant_id"=>"40363426"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Domino'S Pizza", "restaurant_id"=>"40363644"}
...

.. _ruby-return-documents-combine:

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

You can chain the ``limit``, ``sort``, and ``skip`` methods to a single
``find`` method call. This allows you to set a maximum number of sorted documents
to return from the read operation, skipping a specified number of documents before
returning.

The following example returns ``5`` documents that have a ``cuisine`` value of
``'Italian'``. The results are sorted in ascending order by the ``name`` field value,
skipping the first ``10`` documents:

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

.. input:: /includes/read/limit-skip-sort.rb
:start-after: start-limit-sort-skip
:end-before: end-limit-sort-skip
:language: ruby
:dedent:

.. output::
:visible: false

{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Acqua", "restaurant_id"=>"40871070"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Acqua Restaurant",
"restaurant_id"=>"41591488"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Acqua Santa", "restaurant_id"=>"40735858"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Acquista Trattoria",
"restaurant_id"=>"40813992"}
{"_id"=>BSON::ObjectId('...'), ... , "name"=>"Acquolina Catering", "restaurant_id"=>"41381423"}

.. note::

The order in which you call these methods doesn't change the documents
that are returned. The {+driver-short+} automatically reorders the calls to
perform the sort operation first, the skip operation next, and then the limit
operation.

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

For more information about retrieving documents, see the :ref:`ruby-retrieve` guide.

.. TODO: For more information about specifying a query, see the :ref:`ruby-specify-query` guide.

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

To learn more about the ``find`` method and its options, see the `API documentation.
<{+api-root+}/Mongo/Collection.html#find-instance_method>`__
Loading