Skip to content

Commit 26210c4

Browse files
committed
DOCSP-45194: Retrieve data
1 parent e681751 commit 26210c4

File tree

4 files changed

+302
-1
lines changed

4 files changed

+302
-1
lines changed

source/includes/read/retrieve.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
require 'bundler/inline'
2+
3+
gemfile do
4+
source 'https://rubygems.org'
5+
gem 'mongo'
6+
end
7+
8+
uri = '<connection string>'
9+
10+
begin
11+
client = Mongo::Client.new(uri)
12+
13+
# start-db-coll
14+
database = client.use('sample_training')
15+
collection = database[:companies]
16+
# end-db-coll
17+
18+
# Finds one document with a "name" value of "LinkedIn"
19+
# start-find-one
20+
document = collection.find({ 'name' => 'LinkedIn' }).first
21+
puts document
22+
# end-find-one
23+
24+
# Finds documents with a "founded_year" value of 1970
25+
# start-find-many
26+
results = collection.find({ 'founded_year' => 1970 })
27+
# end-find-many
28+
29+
# start-cursor
30+
results.each do |doc|
31+
puts doc
32+
end
33+
# end-cursor
34+
35+
36+
# Finds and prints up to 5 documents with a "number_of_employees" value of 1000
37+
# start-modify
38+
limit_results = collection.find({ 'number_of_employees' => 1000 }).limit(5)
39+
40+
limit_results.each do |doc|
41+
puts doc
42+
end
43+
# end-modify
44+
ensure
45+
client&.close
46+
end
47+

source/index.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414

1515
Get Started </get-started>
1616
Connect </connect>
17+
Read Data </read>
1718
View the Source <https://github.com/mongodb/mongo-ruby-driver>
1819
API Documentation <{+api-root+}>
1920

2021
.. TODO:
2122
Databases & Collections </databases-collections>
22-
Read Data </read>
2323
Write Data </write>
2424
Operations on Replica Sets </read-write-pref>
2525
Indexes </indexes>

source/read.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
.. _ruby-read:
2+
3+
======================
4+
Read Data from MongoDB
5+
======================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:description: Learn how to use the Ruby driver to read data to MongoDB.
19+
:keywords: usage examples, save, crud, read, code example
20+
21+
.. toctree::
22+
:titlesonly:
23+
:maxdepth: 1
24+
25+
Retrieve Data </read/retrieve>

source/read/retrieve.txt

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
.. _ruby-retrieve:
2+
3+
=============
4+
Retrieve Data
5+
=============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: code examples, read, query, cursor
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to retrieve
24+
data from a MongoDB collection by using **read operations**. You can call the
25+
``find`` method on a collection to retrieve documents that match a set of
26+
criteria.
27+
28+
Sample Data
29+
~~~~~~~~~~~
30+
31+
The examples in this guide use the ``companies`` collection in the ``sample_training``
32+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
33+
from your {+language+} application, create a ``Mongo::Client`` object that connects to
34+
an Atlas cluster and assign the following values to your ``database`` and ``collection``
35+
variables:
36+
37+
.. literalinclude:: /includes/read/retrieve.rb
38+
:language: ruby
39+
:dedent:
40+
:start-after: start-db-coll
41+
:end-before: end-db-coll
42+
43+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
44+
:atlas:`Get Started with Atlas </getting-started>` guide.
45+
46+
.. _ruby-retrieve-find:
47+
48+
Find Documents
49+
--------------
50+
51+
To retrieve documents from a collection, use the ``find`` method. This method
52+
takes a **query filter** parameter and returns a ``Mongo::Collection::View`` object,
53+
which represents the query. The driver defers the query execution until you
54+
fetch the results by using methods like ``first`` or ``each``. After you request
55+
the results, the driver sends the query to the server and returns a ``Mongo::Cursor``
56+
object from which you can access the results.
57+
58+
You can chain option methods to the ``find`` method to refine the results of the operation.
59+
60+
.. TODO: To learn more about query filters, see the :ref:`ruby-specify-query` guide.
61+
62+
.. _ruby-retrieve-find-multiple:
63+
64+
Find Multiple Documents
65+
~~~~~~~~~~~~~~~~~~~~~~~
66+
67+
To find multiple documents in a collection, pass a query filter to the
68+
``find`` method that specifies the criteria of the documents you want to retrieve.
69+
70+
The following example uses the ``find`` method to find all documents in which
71+
the ``founded_year`` field has the value ``1970``:
72+
73+
.. literalinclude:: /includes/read/retrieve.rb
74+
:language: ruby
75+
:dedent:
76+
:start-after: start-find-many
77+
:end-before: end-find-many
78+
79+
When you call the ``each`` method on the ``Mongo::Collection::View`` object representing
80+
the query, the driver returns a ``Mongo::Cursor`` object. A cursor is a mechanism that allows an
81+
application to iterate over database results while holding only a subset of them in
82+
memory at a given time. Cursors are useful when your ``find`` method returns a large
83+
amount of documents.
84+
85+
The following code calls the ``each`` method to iterate over the query results:
86+
87+
.. io-code-block::
88+
:copyable:
89+
90+
.. input:: /includes/read/retrieve.rb
91+
:start-after: start-cursor
92+
:end-before: end-cursor
93+
:language: ruby
94+
:dedent:
95+
96+
.. output::
97+
:visible: false
98+
99+
{"_id":{"$oid":"..."},"name":"Mitsubishi Motors","permalink":"mitsubishi-motors",
100+
"crunchbase_url":"http:\/\/www.crunchbase.com\/company\/mitsubishi-motors",
101+
... }
102+
103+
{"_id":{"$oid":"..."},"name":"Western Digital","permalink":"western-digital",
104+
"crunchbase_url":"http:\/\/www.crunchbase.com\/company\/western-digital",
105+
... }
106+
107+
{"_id":{"$oid":"..."},"name":"Celarayn","permalink":"celarayn","crunchbase_url":
108+
"http:\/\/www.crunchbase.com\/company\/celarayn",
109+
... }
110+
111+
.. note:: Find All Documents
112+
113+
To find all documents in a collection, call the ``find`` method
114+
without passing a query filter:
115+
116+
.. code-block:: ruby
117+
118+
results = collection.find
119+
120+
.. _ruby-retrieve-find-one:
121+
122+
Find One Document
123+
~~~~~~~~~~~~~~~~~
124+
125+
To find a single document in a collection, call the ``find`` method and pass a query
126+
filter that specifies the criteria of the document you want to find. Then, chain
127+
the ``first`` method to ``find``.
128+
129+
If the query filter matches more than one document, the ``first`` method retrieves the *first*
130+
matching document from the operation results.
131+
132+
The following example chains the ``first`` method to ``find`` to find the first
133+
document in which the ``name`` field has the value ``'LinkedIn'``:
134+
135+
.. io-code-block::
136+
:copyable:
137+
138+
.. input:: /includes/read/retrieve.rb
139+
:start-after: start-find-one
140+
:end-before: end-find-one
141+
:language: ruby
142+
:dedent:
143+
144+
.. output::
145+
:visible: false
146+
147+
{"_id"=>BSON::ObjectId('...'), "name"=>"LinkedIn", "permalink"=>"linkedin",
148+
"crunchbase_url"=>"http://www.crunchbase.com/company/linkedin",
149+
"homepage_url"=>"http://linkedin.com", "blog_url"=>"http://blog.linkedin.com",
150+
...}
151+
152+
.. tip:: Sort Order
153+
154+
The ``first`` method returns the first document in
155+
:manual:`natural order </reference/glossary/#std-term-natural-order>`
156+
on disk if no sort criteria is specified.
157+
158+
.. _ruby-retrieve-modify:
159+
160+
Modify Find Behavior
161+
~~~~~~~~~~~~~~~~~~~~
162+
163+
You can chain option methods to the ``find`` method to modify the operation
164+
results. The following table describes some of these options:
165+
166+
.. list-table::
167+
:widths: 30 70
168+
:header-rows: 1
169+
170+
* - Option
171+
- Description
172+
173+
* - ``batch_size``
174+
- | The number of documents to return per batch. The default value is ``101``.
175+
| **Type**: ``Integer``
176+
177+
* - ``collation``
178+
- | The collation to use for the operation. The default value is the collation
179+
specified for the collection.
180+
| **Type**: ``Hash``
181+
182+
* - ``comment``
183+
- | The comment to attach to the operation.
184+
| **Type**: ``Object``
185+
186+
* - ``limit``
187+
- | The maximum number of documents the operation can return.
188+
| **Type**: ``Integer``
189+
190+
* - ``skip``
191+
- | The number of documents to skip before returning results.
192+
| **Type**: ``Integer``
193+
194+
* - ``sort``
195+
- | The order in which the operation returns matching documents.
196+
| **Type**: ``Hash``
197+
198+
The following example uses the ``find`` method to find all documents in which
199+
the ``number_of_employees`` field has the value ``1000``. The example uses the
200+
``limit`` option to return a maximum of ``5`` results:
201+
202+
.. literalinclude:: /includes/read/retrieve.rb
203+
:language: ruby
204+
:emphasize-lines: 3
205+
:start-after: start-modify
206+
:end-before: end-modify
207+
208+
For a full list of options, see the API documentation for the
209+
`find <{+api-root}/Mongo/Collection.html#find-instance_method>`__
210+
method.
211+
212+
.. _ruby-retrieve-additional-information:
213+
214+
Additional Information
215+
----------------------
216+
217+
.. TODO:
218+
To learn more about query filters, see the :ref:`ruby-specify-query` guide.
219+
To view code examples of retrieving documents with the {+driver-short+}, see :ref:`ruby-read`.
220+
221+
API Documentation
222+
~~~~~~~~~~~~~~~~~
223+
224+
To learn more about any of the methods or types discussed in this
225+
guide, see the following API documentation:
226+
227+
- `find <{+api-root}/Mongo/Collection.html#find-instance_method>`__
228+
- `Mongo::Collection::View <{+api-root}/Mongo/Collection/View.html>`__
229+
- `Mongo::Cursor <{+api-root}/Mongo/Cursor.html>`__

0 commit comments

Comments
 (0)