Skip to content

Commit 1a70647

Browse files
authored
Merge pull request #117 from gmiller-mdb/DOCSP-45182-ruby-databases-collection-2
Docsp 45182 ruby databases collection 2
2 parents abd60c9 + a0e0b95 commit 1a70647

File tree

3 files changed

+367
-5
lines changed

3 files changed

+367
-5
lines changed

source/databases-collection.txt

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
.. _ruby-databases-collections:
2+
3+
=========================
4+
Databases and Collections
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: table, row, organize, storage
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use MongoDB databases and
24+
collections with {+driver-short+}.
25+
26+
MongoDB organizes data into a hierarchy of the following levels:
27+
28+
- **Databases**: The top level of data organization in a MongoDB instance.
29+
- **Collections**: MongoDB stores documents in collections. They are analogous to tables in relational databases.
30+
- **Documents**: Contain literal data such as string, numbers, dates, and other embedded documents.
31+
32+
For more information about document field types and structure, see the
33+
:manual:`Documents </core/document/>` guide in the {+mdb-server+} manual.
34+
35+
.. TODO: Add a diagram here
36+
37+
Access a Database
38+
-----------------
39+
40+
Access a database by creating a ``Mongo::Client`` instance with the desired
41+
database name.
42+
43+
The following example accesses a database named ``test_database``:
44+
45+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
46+
:language: ruby
47+
:dedent:
48+
:start-after: start-access-db
49+
:end-before: end-access-db
50+
51+
52+
Access a Collection
53+
-------------------
54+
55+
Access a collection by using the ``[]`` method on an instance
56+
of your database.
57+
58+
The following example accesses a collection named ``test_collection``:
59+
60+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
61+
:language: ruby
62+
:dedent:
63+
:emphasize-lines: 2
64+
:start-after: start-access-cl
65+
:end-before: end-access-cl
66+
67+
.. tip::
68+
69+
If the provided collection name does not already exist in the database,
70+
MongoDB implicitly creates the collection when you first insert data
71+
into it.
72+
73+
Create a Collection
74+
-------------------
75+
76+
While the Ruby driver for MongoDB does not have a direct ``create_collection``
77+
method, you can use the ``create`` method to create a collection with
78+
specific options.
79+
80+
The following example creates a collection called example_collection with
81+
specific options:
82+
83+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
84+
:language: ruby
85+
:dedent:
86+
:emphasize-lines: 2
87+
:start-after: start-create-collection
88+
:end-before: end-create-collection
89+
90+
You can specify collection options such as maximum size, document validation
91+
rules, and others by passing them as arguments to the command method with the
92+
create command. For a full list of optional parameters, refer to the MongoDB
93+
documentation on the :manual:`create command </reference/command/create/>`.
94+
95+
Get a List of Collections
96+
-------------------------
97+
98+
You can query for a list of collections in a database by calling the ``collections``
99+
method. This method returns an array of collection objects in the database.
100+
101+
The following example calls the ``collections`` method and iterates over the array
102+
to print the results:
103+
104+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
105+
:language: ruby
106+
:dedent:
107+
:start-after: start-get-list
108+
:end-before: end-get-list
109+
110+
To query for only the names of the collections in the database, call the
111+
``collection_names`` method as follows:
112+
113+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
114+
:language: ruby
115+
:dedent:
116+
:start-after: start-get-list-names
117+
:end-before: end-get-list-names
118+
119+
.. note::
120+
121+
The ``database.collections`` objects list provides more detailed information
122+
(i.e. each collection object can be further queried for metadata), while
123+
``database.collection_names`` simply lists the collection names.
124+
125+
126+
127+
Delete a Collection
128+
-------------------
129+
130+
You can delete a collection from the database by using the ``drop`` method.
131+
132+
The following example deletes the ``test_collection`` collection:
133+
134+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
135+
:language: ruby
136+
:dedent:
137+
:start-after: start-delete
138+
:end-before: end-delete
139+
140+
.. warning:: Dropping a Collection Deletes All Data in the Collection
141+
142+
Dropping a collection from your database permanently deletes all
143+
documents and all indexes within that collection.
144+
145+
Drop a collection only if the data in it is no longer needed.
146+
147+
.. _ruby-config-read-write:
148+
149+
Configure Read and Write Operations
150+
-----------------------------------
151+
152+
You can control how the driver routes read operations by setting a **read preference**.
153+
You can also control options for how the driver waits for acknowledgment of
154+
read and write operations on a replica set by setting a **read concern** and a
155+
**write concern**.
156+
157+
By default, databases inherit these settings from the ``Mongo::Client`` instance,
158+
and collections inherit them from the database. However, you can change these
159+
settings on your database or collection by using one of the following methods:
160+
161+
- ``database.with``: Gets the database and applies the new read preference, read
162+
concern, and write concern.
163+
- ``collection.with``: Gets the collection and applies the new read preference,
164+
read concern, and write concern.
165+
166+
To change read or write settings with the preceding methods, call the method and
167+
pass in the new read preference, read concern, or write concern.
168+
169+
The following example shows how to change the read preference, read concern, and
170+
write preference of a database called ``test-database`` with the ``database.with``
171+
method:
172+
173+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
174+
:language: ruby
175+
:dedent:
176+
:start-after: start-with-database
177+
:end-before: end-with-database
178+
179+
The following example shows how to change the read preference, read concern, and
180+
write concern of a collection:
181+
182+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
183+
:language: ruby
184+
:dedent:
185+
:start-after: start-with-collection
186+
:end-before: end-with-collection
187+
188+
To learn more about the read and write settings, see the following guides in the
189+
MongoDB Server manual:
190+
191+
- :manual:`Read Preference </core/read-preference/>`
192+
- :manual:`Read Concern </reference/read-concern/>`
193+
- :manual:`Write Concern </reference/write-concern/>`
194+
195+
Tag Sets
196+
~~~~~~~~
197+
198+
In {+mdb-server+}, you can apply key-value :manual:`tags
199+
</core/read-preference-tags/>` to replica set
200+
members according to any criteria you choose. You can then use
201+
those tags to target one or more members for a read operation.
202+
203+
By default, the MongoDB {+driver-short+} selects primary members for read operations.
204+
You can modify this behavior by setting read preferences and, optionally, tag sets.
205+
206+
In the following code example, the tag set passed to the ``:read`` parameter
207+
instructs the {+driver-short+} to prefer reads from the New York data center
208+
(``'dc':'ny'``) and to fall back to the San Francisco data center (``'dc':'sf'``):
209+
210+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
211+
:language: ruby
212+
:dedent:
213+
:start-after: start-tag-sets
214+
:end-before: end-tag-sets
215+
216+
To learn more about replica sets, see the the MongoDB Server manual
217+
:manual:`Replica Set Members </core/replica-set-members/>` page.
218+
219+
Local Threshold
220+
~~~~~~~~~~~~~~~
221+
222+
If multiple replica set members match the read preference and tag sets you specify,
223+
{+driver-short+} reads from the nearest replica set members of sharded clusters,
224+
chosen according to their ping time.
225+
226+
By default, the driver uses only those members whose ping times are within 15 milliseconds
227+
of the nearest member for queries. To distribute reads between members with
228+
higher latencies, pass the ``local_threshold`` option to the ``Mongo::Client`` constructor.
229+
230+
The following example specifies a local threshold of 35 milliseconds:
231+
232+
.. literalinclude:: /includes/usage-examples/databases-collection.rb
233+
:language: ruby
234+
:dedent:
235+
:start-after: start-local-threshold-example
236+
:end-before: end-local-threshold-example
237+
:emphasize-lines: 5
238+
239+
In the preceding example, {+driver-short+} distributes reads between matching members
240+
within 35 milliseconds of the closest member's ping time.
241+
242+
.. note::
243+
244+
{+driver-short+} ignores the value of ``local_threshold`` when communicating with a
245+
replica set through a ``mongos`` instance. In this case, use the
246+
:manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>`
247+
command-line option.
248+
249+
.. TODO:
250+
.. Troubleshooting
251+
.. ---------------
252+
253+
.. .. include:: /includes/usage-examples/databases-collection.rb
254+
255+
API Documentation
256+
-----------------
257+
258+
To learn more about any of the methods or types discussed in this
259+
guide, see the following API documentation:
260+
261+
- `collections <{+api-root+}/Mongo/Database.html#collections-instance_method>`__
262+
- `collection_names <{+api-root+}/Mongo/Database.html#collection_names-instance_method>`__
263+
- `command <{+api-root+}/Mongo/Monitoring/Event/CommandStarted.html#command-instance_method>`__
264+
- `drop database <{+api-root+}/Mongo/Database.html#drop-instance_method>`__
265+
- `drop collection <{+api-root+}/Mongo/Collection.html#drop-instance_method>`__
266+
- `with <{+api-root+}/Mongo/Collection.html#with-instance_method>`__
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
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+
Mongo::Client.new(uri) do |client|
11+
# start-access-db
12+
client = Mongo::Client.new(['127.0.0.1:27017'], database: 'test_database')
13+
database = client.database
14+
# end-access-db
15+
16+
# start-access-cl
17+
database = client.database
18+
collection = database['test_collection']
19+
# end-access-cl
20+
21+
# start-create-collection
22+
database = client.database
23+
24+
database[:example_collection].create(capped: true, size: 1024)
25+
# end-create-collection
26+
27+
# start-get-list
28+
database = client.database
29+
30+
collection_list = database.collections
31+
32+
collection_list.each do |collection|
33+
puts collection.name
34+
end
35+
# end-get-list
36+
37+
# start-get-list-names
38+
database = client.database
39+
40+
collection_names = database.collection_names
41+
42+
collection_names.each do |name|
43+
puts name
44+
end
45+
# end-get-list-names
46+
47+
# start-delete
48+
database = client.database
49+
50+
collection = database[:test_collection]
51+
collection.drop
52+
# end-delete
53+
54+
# start-with-database
55+
database_with_settings = client.use('test_database').with(
56+
read: { mode: :secondary },
57+
read_concern: { level: :local },
58+
write: { w: :majority }
59+
)
60+
# end-with-database
61+
62+
# start-with-collection
63+
64+
collection_with_settings = client[:test_collection].with(
65+
read: { mode: :secondary },
66+
read_concern: { level: :local },
67+
write: { w: :majority }
68+
)
69+
# end-with-collection
70+
71+
# start-tag-sets
72+
client = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'test', read: {
73+
mode: :secondary,
74+
tag_sets: [{'dc' => 'ny'}, {'dc' => 'sf'}]
75+
})
76+
77+
database = client.database
78+
79+
collection = database[:example_collection]
80+
# end-tag-sets
81+
82+
# start-local-threshold-example
83+
client = Mongo::Client.new(
84+
['IP_ADDRESS_001:27017'],
85+
database: 'test_database',
86+
read: { mode: :secondary_preferred },
87+
local_threshold: 35
88+
)
89+
90+
database = client.database
91+
92+
collection = database[:example_collection]
93+
result = collection.find({}).first
94+
puts result
95+
# end-local-threshold-example
96+
end

source/index.txt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@
2121
API Documentation <{+api-root+}>
2222
What's New </whats-new>
2323
Compatibility </compatibility>
24+
Databases & Collections </databases-collection>
2425

2526
.. TODO:
26-
Databases & Collections </databases-collections>
2727
Write Data </write>
2828
Operations on Replica Sets </read-write-pref>
2929
Monitor Your Application </monitoring>
@@ -50,11 +50,11 @@ working with data in the :ref:`ruby-get-started` tutorial.
5050
.. Learn how to create and configure a connection to a MongoDB deployment
5151
.. in the :ref:`ruby-connect` section.
5252

53-
.. Databases and Collections
54-
.. -------------------------
53+
Databases and Collections
54+
-------------------------
5555

56-
.. Learn how to use the {+driver-short+} to work with MongoDB databases and collections in the
57-
.. :ref:`ruby-databases-collections` section.
56+
Learn how to use the {+driver-short+} to work with MongoDB databases and collections in the
57+
:ref:`ruby-databases-collections` section.
5858

5959
.. Read Data from MongoDB
6060
.. ----------------------

0 commit comments

Comments
 (0)