Skip to content

Commit aa221f9

Browse files
committed
DOCSP-45187: Update
1 parent e681751 commit aa221f9

File tree

4 files changed

+337
-1
lines changed

4 files changed

+337
-1
lines changed

snooty.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ name = "ruby-driver"
22
title = "Ruby MongoDB Driver"
33
toc_landing_pages = [
44
"/get-started",
5-
"/connect"
5+
"/connect",
6+
"/write"
67
]
78

89
intersphinx = ["https://www.mongodb.com/docs/manual/objects.inv"]

source/includes/write/update.rb

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
require 'bundler/inline'
2+
gemfile do
3+
source 'https://rubygems.org'
4+
gem 'mongo'
5+
end
6+
7+
uri = "<connection string URI>"
8+
9+
begin
10+
client = Mongo::Client.new(uri)
11+
12+
# start-db-coll
13+
database = client.use('sample_restaurants')
14+
collection = database[:restaurants]
15+
# end-db-coll
16+
17+
# Updates a single document
18+
# start-update-one
19+
filter = { 'name' => 'Happy Garden' }
20+
21+
update = { '$set' => { 'name' => 'Mountain House' } }
22+
23+
single_result = collection.update_one(filter, update)
24+
25+
puts "#{single_result.modified_count} document(s) updated."
26+
# end-update-one
27+
28+
# Updates multiple documents
29+
# start-update-many
30+
filter = { 'name' => 'Starbucks' }
31+
32+
update = { '$rename' => { 'address' => 'location' } }
33+
34+
many_result = collection.update_many(filter, update)
35+
36+
puts "#{many_result.modified_count} document(s) updated."
37+
# end-update-many
38+
39+
# start-update-options
40+
filter = { 'name' => 'Sunrise Pizzeria' }
41+
42+
update = { '$set' => { 'borough' => 'Queens', 'cuisine' => 'Italian' } }
43+
44+
upsert_result = collection.update_one(filter, update, upsert: true)
45+
46+
puts "#{upsert_result.modified_count} document(s) updated."
47+
# end-update-options
48+
49+
ensure
50+
client&.close
51+
end

source/write.txt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
.. _ruby-write:
2+
3+
=====================
4+
Write Data to 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 write data to MongoDB.
19+
:keywords: usage examples, save, crud, create, code example
20+
21+
.. toctree::
22+
:titlesonly:
23+
:maxdepth: 1
24+
25+
/write/insert
26+
/write/replace
27+
/write/update
28+
/write/delete
29+
/write/bulk-write
30+
/write/transactions
31+
/write/gridfs
32+
33+
.. TODO

source/write/update.txt

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
.. _ruby-write-update:
2+
3+
================
4+
Update Documents
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: modify, change, operator, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to update
24+
documents in a MongoDB collection by using the ``update_one()`` and
25+
``update_many()`` methods.
26+
27+
Sample Data
28+
~~~~~~~~~~~
29+
30+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
31+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
32+
from your {+language+} application, create a ``Mongo::Client`` that connects to an Atlas cluster
33+
and assign the following values to your ``database`` and ``collection`` variables:
34+
35+
.. literalinclude:: /includes/write/update.rb
36+
:language: ruby
37+
:dedent:
38+
:start-after: start-db-coll
39+
:end-before: end-db-coll
40+
41+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
42+
:atlas:`Get Started with Atlas </getting-started>` guide.
43+
44+
Update Operations
45+
-----------------
46+
47+
You can update documents in MongoDB by using the following methods:
48+
49+
- ``update_one()``, which updates *the first document* that matches the search criteria
50+
- ``update_many()``, which updates *all documents* that match the search criteria
51+
52+
Each update method requires the following parameters:
53+
54+
- **Query filter**, which matches the documents you want to update. To learn
55+
more about query filters, see the :ref:`ruby-specify-query`
56+
guide.
57+
58+
- **Update document**, which specifies the update operator and the fields and values to be
59+
updated. The update operator specifies the type of update to perform. To view a list of
60+
update operators and learn about their usages, see the
61+
:manual:`Field Update Operators guide page</reference/operator/update-field/>` in the
62+
{+mdb-server+} manual.
63+
64+
Update One Document Example
65+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
66+
67+
The following example uses the ``update_one()`` method to update the
68+
``name`` field value of a document from ``"Happy Garden"`` to ``"Mountain
69+
House"``. The update document uses the ``$set`` operation to update the ``name`` field
70+
value:
71+
72+
.. io-code-block::
73+
:copyable: true
74+
75+
.. input:: /includes/write/update.rb
76+
:start-after: start-update-one
77+
:end-before: end-update-one
78+
:emphasize-lines: 3
79+
:language: ruby
80+
:dedent:
81+
82+
.. output::
83+
:language: console
84+
:visible: false
85+
86+
1 document(s) updated
87+
88+
Update Many Documents Example
89+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90+
91+
The following example uses the ``update_many()`` method to update all documents
92+
in which the ``name`` field value is ``"Starbucks"``. The update document uses the
93+
``rename()`` method to change the name of the ``address`` field to ``location``:
94+
95+
.. io-code-block::
96+
:copyable: true
97+
98+
.. input:: /includes/write/update.rb
99+
:start-after: start-update-many
100+
:end-before: end-update-many
101+
:emphasize-lines: 3
102+
:language: ruby
103+
:dedent:
104+
105+
.. output::
106+
:language: console
107+
:visible: false
108+
109+
11 document(s) updated
110+
111+
Customize the Update Operation
112+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
113+
114+
The ``update_one()`` and ``update_many()`` methods accept options to configure the update
115+
operation. You can pass these options individually as parameters, or you can create a
116+
``Hash`` object that contains the options and pass it as a parameter.
117+
If you don't specify any options, the driver performs update
118+
operations with default settings.
119+
120+
The following table describes the options that you can use to
121+
configure the update operation:
122+
123+
.. list-table::
124+
:widths: 30 70
125+
:header-rows: 1
126+
127+
* - Option
128+
- Description
129+
130+
* - ``upsert``
131+
- | Specifies whether the update operation performs an upsert operation if no
132+
documents match the query filter. For more information, see the :manual:`upsert
133+
statement </reference/command/update/#std-label-update-command-upsert>`
134+
in the {+mdb-server+} manual.
135+
| Defaults to ``false``
136+
137+
* - ``bypass_document_validation``
138+
- | Specifies whether the update operation bypasses document validation. This lets you
139+
update documents that don't meet the schema validation requirements, if any
140+
exist. For more information about schema validation, see :manual:`Schema
141+
Validation </core/schema-validation/#schema-validation>` in the MongoDB
142+
Server manual.
143+
| Defaults to ``false``.
144+
145+
* - ``collation``
146+
- | Specifies the kind of language collation to use when sorting
147+
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
148+
in the {+mdb-server+} manual.
149+
150+
* - ``array_filters``
151+
- | Provides a list of filters that you specify to select which
152+
array elements the update applies to.
153+
154+
* - ``hint``
155+
- | Sets the index to use when matching documents.
156+
For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
157+
in the {+mdb-server+} manual.
158+
159+
* - ``let``
160+
- | Provides a map of parameter names and values to set top-level
161+
variables for the operation. Values must be constant or closed
162+
expressions that don't reference document fields. For more information,
163+
see the :manual:`let statement
164+
</reference/command/update/#std-label-update-let-syntax>` in the
165+
{+mdb-server+} manual.
166+
167+
Modify Update Example
168+
`````````````````````
169+
170+
This example creates and passes options to the ``update_one()`` method.
171+
The example uses the ``$equal`` operation to match documents
172+
in which the ``name`` field value is ``"Sunrise Pizzeria"``. It then uses the ``$set``
173+
operation to set the ``borough`` field value in the first matching document to
174+
``"Queens"`` and the ``cuisine`` field value to ``"Italian"``.
175+
176+
Because the ``upsert`` option is set to ``true``, the driver inserts a new document that
177+
has the fields and values specified in the filter and update document if the query filter
178+
doesn't match any existing documents.
179+
180+
.. io-code-block::
181+
:copyable: true
182+
183+
.. input:: /includes/write/update.rb
184+
:start-after: start-update-options
185+
:end-before: end-update-options
186+
:language: ruby
187+
:emphasize-lines: 2
188+
:dedent:
189+
190+
.. output::
191+
:language: console
192+
:visible: false
193+
194+
1 document(s) updated
195+
196+
Return Value
197+
~~~~~~~~~~~~
198+
199+
The ``update_one()`` and ``update_many()`` methods each return a ``Result``
200+
object. You can use the access the following instance methods from a ``Result`` instance:
201+
202+
.. list-table::
203+
:widths: 30 70
204+
:header-rows: 1
205+
206+
* - Method
207+
- Description
208+
209+
* - ``matched_count``
210+
- | Returns the number of documents that matched the query filter, regardless of
211+
how many updates were performed.
212+
213+
* - ``modified_count``
214+
- | Returns the number of documents modified by the update operation. If an updated
215+
document is identical to the original, it is not included in this
216+
count.
217+
218+
* - ``acknowledged?``
219+
- | Returns ``true`` if the server acknowledged the result.
220+
221+
* - ``upserted_count``
222+
- | Returns the number of documents that were upserted in the database, if the driver
223+
performed an upsert.
224+
225+
* - ``upserted_ids``
226+
- | Returns the ``_id`` value of the document that was upserted
227+
in the database, if the driver performed an upsert.
228+
229+
.. note::
230+
231+
If the ``acknowledged?`` method returns ``false``, trying to
232+
access other information from the ``Result`` instance results in an
233+
``InvalidOperation`` exception. The driver cannot
234+
determine these values if the server does not acknowledge the write
235+
operation.
236+
237+
Additional Information
238+
----------------------
239+
240+
To view runnable code examples that demonstrate how to update documents by
241+
using the {+driver-short+}, see :ref:`ruby-write`.
242+
243+
API Documentation
244+
~~~~~~~~~~~~~~~~~
245+
246+
To learn more about any of the methods or types discussed in this
247+
guide, see the following API documentation:
248+
249+
- `update_one() <{+api-root+}/Mongo/Collection.html#update_one-instance_method>`_
250+
- `update_many() <{+api-root+}/Mongo/Collection.html#update_many-instance_method>`_
251+
- `Result <{+api-root+}/Mongo/Operation/Update/Result.html>`_

0 commit comments

Comments
 (0)