File: writable.rb

package info (click to toggle)
ruby-mongo 2.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,764 kB
  • sloc: ruby: 108,806; makefile: 5; sh: 2
file content (652 lines) | stat: -rw-r--r-- 29,441 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
# frozen_string_literal: true
# rubocop:todo all

# Copyright (C) 2014-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

module Mongo
  class Collection
    class View

      # Defines write related behavior for collection view.
      #
      # @since 2.0.0
      module Writable

        # The array filters field constant.
        #
        # @since 2.5.0
        ARRAY_FILTERS = 'array_filters'.freeze

        # Finds a single document in the database via findAndModify and deletes
        # it, returning the original document.
        #
        # @example Find one document and delete it.
        #   view.find_one_and_delete
        #
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Integer ] :max_time_ms The maximum amount of time to allow the command
        #   to run in milliseconds. This option is deprecated, use
        #   :timeout_ms instead.
        # @option opts [ Hash ] :projection The fields to include or exclude in the returned doc.
        # @option opts [ Hash ] :sort The key and direction pairs by which the result set
        #   will be sorted.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Session ] :session The session to use.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        #
        # @return [ BSON::Document, nil ] The document, if found.
        #
        # @since 2.0.0
        def find_one_and_delete(opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end

            QueryCache.clear_namespace(collection.namespace)

            cmd = {
              findAndModify: collection.name,
              query: filter,
              remove: true,
              fields: projection,
              sort: sort,
              maxTimeMS: max_time_ms,
              bypassDocumentValidation: opts[:bypass_document_validation],
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
              let: opts[:let],
              comment: opts[:comment],
            }.compact

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_4 = connection.server.description.server_version_gte?('4.4')
              if !gte_4_4 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::WriteCommand.new(
                selector: cmd,
                db_name: database.name,
                write_concern: write_concern,
                session: session,
                txn_num: txn_num,
              ).execute_with_connection(connection, context: context)
            end
          end.first&.fetch('value', nil)
        end

        # Finds a single document and replaces it.
        #
        # @example Find a document and replace it, returning the original.
        #   view.find_one_and_replace({ name: 'test' }, :return_document => :before)
        #
        # @example Find a document and replace it, returning the new document.
        #   view.find_one_and_replace({ name: 'test' }, :return_document => :after)
        #
        # @param [ BSON::Document ] replacement The replacement.
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Symbol ] :return_document Either :before or :after.
        # @option opts [ true, false ] :upsert Whether to upsert if the document doesn't exist.
        # @option opts [ true, false ] :bypass_document_validation Whether or
        #   not to skip document level validation.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        #
        # @return [ BSON::Document ] The document.
        #
        # @since 2.0.0
        def find_one_and_replace(replacement, opts = {})
          find_one_and_update(replacement, opts)
        end

        # Finds a single document and updates it.
        #
        # @example Find a document and update it, returning the original.
        #   view.find_one_and_update({ "$set" => { name: 'test' }}, :return_document => :before)
        #
        # @param [ BSON::Document ] document The updates.
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Integer ] :max_time_ms The maximum amount of time to allow the command
        #   to run in milliseconds. This option is deprecated, use
        #   :timeout_ms instead.
        # @option opts [ Hash ] :projection The fields to include or exclude in the returned doc.
        # @option opts [ Hash ] :sort The key and direction pairs by which the result set
        #   will be sorted.
        # @option opts [ Symbol ] :return_document Either :before or :after.
        # @option opts [ true, false ] :upsert Whether to upsert if the document doesn't exist.
        # @option opts [ true, false ] :bypass_document_validation Whether or
        #   not to skip document level validation.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Array ] :array_filters A set of filters specifying to which array elements
        # an update should apply.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        #
        # @return [ BSON::Document | nil ] The document or nil if none is found.
        #
        # @since 2.0.0
        def find_one_and_update(document, opts = {})
          value = with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end

            QueryCache.clear_namespace(collection.namespace)

            cmd = {
              findAndModify: collection.name,
              query: filter,
              arrayFilters: opts[:array_filters] || opts['array_filters'],
              update: document,
              fields: projection,
              sort: sort,
              new: !!(opts[:return_document] && opts[:return_document] == :after),
              upsert: opts[:upsert],
              maxTimeMS: max_time_ms,
              bypassDocumentValidation: opts[:bypass_document_validation],
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
              let: opts[:let],
              comment: opts[:comment]
            }.compact

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_4 = connection.server.description.server_version_gte?('4.4')
              if !gte_4_4 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::WriteCommand.new(
                selector: cmd,
                db_name: database.name,
                write_concern: write_concern,
                session: session,
                txn_num: txn_num,
              ).execute_with_connection(connection, context: context)
            end
          end.first&.fetch('value', nil)
          value unless value.nil? || value.empty?
        end

        # Remove documents from the collection.
        #
        # @example Remove multiple documents from the collection.
        #   collection_view.delete_many
        #
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        #
        # @return [ Result ] The response from the database.
        #
        # @since 2.0.0
        def delete_many(opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end

            QueryCache.clear_namespace(collection.namespace)

            delete_doc = {
              Operation::Q => filter,
              Operation::LIMIT => 0,
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
            }.compact
            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            nro_write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_4 = connection.server.description.server_version_gte?('4.4')
              if !gte_4_4 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::Delete.new(
                deletes: [ delete_doc ],
                db_name: collection.database.name,
                coll_name: collection.name,
                write_concern: write_concern,
                bypass_document_validation: !!opts[:bypass_document_validation],
                session: session,
                let: opts[:let],
                comment: opts[:comment],
              ).execute_with_connection(connection, context: context)
            end
          end
        end

        # Remove a document from the collection.
        #
        # @example Remove a single document from the collection.
        #   collection_view.delete_one
        #
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        #
        # @return [ Result ] The response from the database.
        #
        # @since 2.0.0
        def delete_one(opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end

            QueryCache.clear_namespace(collection.namespace)

            delete_doc = {
              Operation::Q => filter,
              Operation::LIMIT => 1,
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
            }.compact

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_4 = connection.server.description.server_version_gte?('4.4')
              if !gte_4_4 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::Delete.new(
                deletes: [ delete_doc ],
                db_name: collection.database.name,
                coll_name: collection.name,
                write_concern: write_concern,
                bypass_document_validation: !!opts[:bypass_document_validation],
                session: session,
                txn_num: txn_num,
                let: opts[:let],
                comment: opts[:comment],
              ).execute_with_connection(connection, context: context)
            end
          end
        end

        # Replaces a single document in the database with the new document.
        #
        # @example Replace a single document.
        #   collection_view.replace_one({ name: 'test' })
        #
        # @param [ Hash ] replacement The replacement document.
        # @param [ Hash ] opts The options.
        #
        # @option opts [ true, false ] :bypass_document_validation Whether or
        #   not to skip document level validation.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ Hash ] :write_concern The write concern options.
        # @option opts [ true, false ] :upsert Whether to upsert if the
        #   document doesn't exist.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        #
        # @return [ Result ] The response from the database.
        #
        # @since 2.0.0
        def replace_one(replacement, opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end
            validate_replacement_documents!(replacement)

            QueryCache.clear_namespace(collection.namespace)

            update_doc = {
              Operation::Q => filter,
              arrayFilters: opts[:array_filters] || opts['array_filters'],
              Operation::U => replacement,
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
            }.compact
            if opts[:upsert]
              update_doc['upsert'] = true
            end

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_2 = connection.server.description.server_version_gte?('4.2')
              if !gte_4_2 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::Update.new(
                updates: [ update_doc ],
                db_name: collection.database.name,
                coll_name: collection.name,
                write_concern: write_concern,
                bypass_document_validation: !!opts[:bypass_document_validation],
                session: session,
                txn_num: txn_num,
                let: opts[:let],
                comment: opts[:comment],
              ).execute_with_connection(connection, context: context)
            end
          end
        end

        # Update documents in the collection.
        #
        # @example Update multiple documents in the collection.
        #   collection_view.update_many('$set' => { name: 'test' })
        #
        # @param [ Hash | Array<Hash> ] spec The update document or pipeline.
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Array ] :array_filters A set of filters specifying to
        #   which array elements an update should apply.
        # @option opts [ true, false ] :bypass_document_validation Whether or
        #   not to skip document level validation.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ true, false ] :upsert Whether to upsert if the
        #   document doesn't exist.
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        #
        # @return [ Result ] The response from the database.
        #
        # @since 2.0.0
        def update_many(spec, opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end
            validate_update_documents!(spec)

            QueryCache.clear_namespace(collection.namespace)

            update_doc = {
              Operation::Q => filter,
              arrayFilters: opts[:array_filters] || opts['array_filters'],
              Operation::U => spec,
              Operation::MULTI => true,
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
            }.compact
            if opts[:upsert]
              update_doc['upsert'] = true
            end

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            nro_write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_2 = connection.server.description.server_version_gte?('4.2')
              if !gte_4_2 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::Update.new(
                updates: [ update_doc ],
                db_name: collection.database.name,
                coll_name: collection.name,
                write_concern: write_concern,
                bypass_document_validation: !!opts[:bypass_document_validation],
                session: session,
                let: opts[:let],
                comment: opts[:comment],
              ).execute_with_connection(connection, context: context)
            end
          end
        end

        # Update a single document in the collection.
        #
        # @example Update a single document in the collection.
        #   collection_view.update_one('$set' => { name: 'test' })
        #
        # @param [ Hash | Array<Hash> ] spec The update document or pipeline.
        # @param [ Hash ] opts The options.
        #
        # @option opts [ Array ] :array_filters A set of filters specifying to
        #   which array elements an update should apply.
        # @option opts [ true, false ] :bypass_document_validation Whether or
        #   not to skip document level validation.
        # @option opts [ Hash ] :collation The collation to use.
        # @option opts [ Object ] :comment A user-provided
        #   comment to attach to this command.
        # @option opts [ Hash | String ] :hint The index to use for this operation.
        #   May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. "_id_").
        # @option opts [ Hash ] :let Mapping of variables to use in the command.
        #   See the server documentation for details.
        # @option opts [ Session ] :session The session to use.
        # @option options [ Integer ] :timeout_ms The operation timeout in milliseconds.
        #    Must be a non-negative integer. An explicit value of 0 means infinite.
        #    The default value is unset which means the value is inherited from
        #    the collection or the database or the client.
        # @option opts [ true, false ] :upsert Whether to upsert if the
        #   document doesn't exist.
        # @option opts [ Hash ] :write_concern The write concern options.
        #   Can be :w => Integer, :fsync => Boolean, :j => Boolean.
        #
        # @return [ Result ] The response from the database.
        #
        # @since 2.0.0
        def update_one(spec, opts = {})
          with_session(opts) do |session|
            write_concern = if opts[:write_concern]
              WriteConcern.get(opts[:write_concern])
            else
              write_concern_with_session(session)
            end
            validate_update_documents!(spec)

            QueryCache.clear_namespace(collection.namespace)

            update_doc = {
              Operation::Q => filter,
              arrayFilters: opts[:array_filters] || opts['array_filters'],
              Operation::U => spec,
              hint: opts[:hint],
              collation: opts[:collation] || opts['collation'] || collation,
            }.compact
            if opts[:upsert]
              update_doc['upsert'] = true
            end

            context = Operation::Context.new(
              client: client,
              session: session,
              operation_timeouts: operation_timeouts(opts)
            )
            write_with_retry(write_concern, context: context) do |connection, txn_num, context|
              gte_4_2 = connection.server.description.server_version_gte?('4.2')
              if !gte_4_2 && opts[:hint] && write_concern && !write_concern.acknowledged?
                raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
              end

              Operation::Update.new(
                updates: [ update_doc ],
                db_name: collection.database.name,
                coll_name: collection.name,
                write_concern: write_concern,
                bypass_document_validation: !!opts[:bypass_document_validation],
                session: session,
                txn_num: txn_num,
                let: opts[:let],
                comment: opts[:comment],
              ).execute_with_connection(connection, context: context)
            end
          end
        end

        private

        # Checks the update documents to make sure they only have atomic modifiers.
        # Note that as per the spec, we only have to examine the first element
        # in the update document.
        #
        # @param [ Hash | Array<Hash> ] spec The update document or pipeline.
        #
        # @raise [ Error::InvalidUpdateDocument ] if the first key in the
        #   document does not start with a $.
        def validate_update_documents!(spec)
          if update = spec.is_a?(Array) ? spec&.first : spec
            if key = update.keys&.first
              unless key.to_s.start_with?("$")
                if Mongo.validate_update_replace
                  raise Error::InvalidUpdateDocument.new(key: key)
                else
                  Error::InvalidUpdateDocument.warn(Logger.logger, key)
                end
              end
            end
          end
        end

        # Check the replacement documents to make sure they don't have atomic
        # modifiers. Note that as per the spec, we only have to examine the
        # first element in the replacement document.
        #
        # @param [ Hash | Array<Hash> ] spec The replacement document or pipeline.
        #
        # @raise [ Error::InvalidUpdateDocument ] if the first key in the
        #   document does not start with a $.
        def validate_replacement_documents!(spec)
          if replace = spec.is_a?(Array) ? spec&.first : spec
            if key = replace.keys&.first
              if key.to_s.start_with?("$")
                if Mongo.validate_update_replace
                  raise Error::InvalidReplacementDocument.new(key: key)
                else
                  Error::InvalidReplacementDocument.warn(Logger.logger, key)
                end
              end
            end
          end
        end
      end
    end
  end
end