Method: Mongo::Collection::View::Writable#update_many

Defined in:
lib/mongo/collection/view/writable.rb

#update_many(spec, opts = {}) ⇒ Result

Update documents in the collection.

Examples:

Update multiple documents in the collection.

collection_view.update_many('$set' => { name: 'test' })

Options Hash (opts):

  • :array_filters (Array)

    A set of filters specifying to which array elements an update should apply.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

  • :session (Session)

    The session to use.

  • :upsert (true, false)

    Whether to upsert if the document doesn’t exist.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

Since:

  • 2.0.0



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
# File 'lib/mongo/collection/view/writable.rb', line 482

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