NAME

MongoDB::Collection - A MongoDB Collection

VERSION

version v2.2.2

SYNOPSIS

# get a Collection via the Database object
$coll = $db->get_collection("people");

# insert a document
$coll->insert_one( { name => "John Doe", age => 42 } );

# insert one or more documents
$coll->insert_many( \@documents );

# delete a document
$coll->delete_one( { name => "John Doe" } );

# update a document
$coll->update_one( { name => "John Doe" }, { '$inc' => { age => 1 } } );

# find a single document
$doc = $coll->find_one( { name => "John Doe" } )

# Get a MongoDB::Cursor for a query
$cursor = $coll->find( { age => 42 } );

# Cursor iteration
while ( my $doc = $cursor->next ) {
    ...
}

DESCRIPTION

This class models a MongoDB collection and provides an API for interacting with it.

Generally, you never construct one of these directly with new. Instead, you call get_collection on a MongoDB::Database object.

USAGE

Error handling

Unless otherwise explicitly documented, all methods throw exceptions if an error occurs. The error types are documented in MongoDB::Error.

To catch and handle errors, the Try::Tiny and Safe::Isa modules are recommended:

use Try::Tiny;
use Safe::Isa; # provides $_isa

try {
    $coll->insert_one( $doc )
}
catch {
    if ( $_->$_isa("MongoDB::DuplicateKeyError" ) {
        ...
    }
    else {
        ...
    }
};

To retry failures automatically, consider using Try::Tiny::Retry.

Transactions

To conduct operations in a transactions, get a MongoDB::ClientSession from "start_session" in MongoDB::MongoClient. Start the transaction on the session using start_transaction and pass the session as an option to all operations. Then call commit_transaction or abort_transaction on the session. See the MongoDB::ClientSession for options and usage details.

For detailed instructions on using transactions with MongoDB, see the MongoDB manual page: Transactions.

Terminology

Document

A collection of key-value pairs. A Perl hash is a document. Array references with an even number of elements and Tie::IxHash objects may also be used as documents.

Ordered document

Many MongoDB::Collection method parameters or options require an ordered document: an ordered list of key/value pairs. Perl's hashes are not ordered and since Perl v5.18 are guaranteed to have random order. Therefore, when an ordered document is called for, you may use an array reference of pairs or a Tie::IxHash object. You may use a hash reference if there is only one key/value pair.

Filter expression

A filter expression provides the query criteria to select a document for deletion. It must be an "Ordered document".

ATTRIBUTES

database

The MongoDB::Database representing the database that contains the collection.

name

The name of the collection.

read_preference

A MongoDB::ReadPreference object. It may be initialized with a string corresponding to one of the valid read preference modes or a hash reference that will be coerced into a new MongoDB::ReadPreference object. By default it will be inherited from a MongoDB::Database object.

write_concern

A MongoDB::WriteConcern object. It may be initialized with a hash reference that will be coerced into a new MongoDB::WriteConcern object. By default it will be inherited from a MongoDB::Database object.

read_concern

A MongoDB::ReadConcern object. May be initialized with a hash reference or a string that will be coerced into the level of read concern.

By default it will be inherited from a MongoDB::Database object.

max_time_ms

Specifies the default maximum amount of time in milliseconds that the server should use for working on a query.

Note: this will only be used for server versions 2.6 or greater, as that was when the $maxTimeMS meta-operator was introduced.

bson_codec

An object that provides the encode_one and decode_one methods, such as from BSON. It may be initialized with a hash reference that will be coerced into a new BSON object. By default it will be inherited from a MongoDB::Database object.

METHODS

client

$client = $coll->client;

Returns the MongoDB::MongoClient object associated with this object.

full_name

$full_name = $coll->full_name;

Returns the full name of the collection, including the namespace of the database it's in prefixed with a dot character. E.g. collection "foo" in database "test" would result in a full_name of "test.foo".

indexes

$indexes = $collection->indexes;

$collection->indexes->create_one( [ x => 1 ], { unique => 1 } );
$collection->indexes->drop_all;

Returns a MongoDB::IndexView object for managing the indexes associated with the collection.

clone

$coll2 = $coll1->clone( write_concern => { w => 2 } );

Constructs a copy of the original collection, but allows changing attributes in the copy.

with_codec

$coll2 = $coll1->with_codec( $new_codec );
$coll2 = $coll1->with_codec( prefer_numeric => 1 );

Constructs a copy of the original collection, but clones the bson_codec. If given an object that does encode_one and decode_one, it is equivalent to:

$coll2 = $coll1->clone( bson_codec => $new_codec );

If given a hash reference or a list of key/value pairs, it is equivalent to:

$coll2 = $coll1->clone(
    bson_codec => $coll1->bson_codec->clone( @list )
);

insert_one

$res = $coll->insert_one( $document );
$res = $coll->insert_one( $document, $options );
$id = $res->inserted_id;

Inserts a single document into the database and returns a MongoDB::InsertOneResult or MongoDB::UnacknowledgedResult object.

If no _id field is present, one will be added when a document is serialized for the database without modifying the original document. The generated _id may be retrieved from the result object.

An optional hash reference of options may be given.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

insert_many

$res = $coll->insert_many( [ @documents ] );
$res = $coll->insert_many( [ @documents ], { ordered => 0 } );

Inserts each of the documents in an array reference into the database and returns a MongoDB::InsertManyResult or MongoDB::UnacknowledgedResult. This is syntactic sugar for doing a MongoDB::BulkWrite operation.

If no _id field is present, one will be added when a document is serialized for the database without modifying the original document. The generated _id may be retrieved from the result object.

An optional hash reference of options may be provided.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • ordered – when true, the server will halt insertions after the first error (if any). When false, all documents will be processed and any error will only be thrown after all insertions are attempted. The default is true.

On MongoDB servers before version 2.6, insert_many bulk operations are emulated with individual inserts to capture error information. On 2.6 or later, this method will be significantly faster than individual insert_one calls.

delete_one

$res = $coll->delete_one( $filter );
$res = $coll->delete_one( { _id => $id } );
$res = $coll->delete_one( $filter, { collation => { locale => "en_US" } } );

Deletes a single document that matches a filter expression and returns a MongoDB::DeleteResult or MongoDB::UnacknowledgedResult object.

A hash reference of options may be provided.

Valid options include:

delete_many

$res = $coll->delete_many( $filter );
$res = $coll->delete_many( { name => "Larry" } );
$res = $coll->delete_many( $filter, { collation => { locale => "en_US" } } );

Deletes all documents that match a filter expression and returns a MongoDB::DeleteResult or MongoDB::UnacknowledgedResult object.

Valid options include:

replace_one

$res = $coll->replace_one( $filter, $replacement );
$res = $coll->replace_one( $filter, $replacement, { upsert => 1 } );

Replaces one document that matches a filter expression and returns a MongoDB::UpdateResult or MongoDB::UnacknowledgedResult object.

The replacement document must not have any field-update operators in it (e.g. $set).

A hash reference of options may be provided.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • upsert – defaults to false; if true, a new document will be added if one is not found

update_one

$res = $coll->update_one( $filter, $update );
$res = $coll->update_one( $filter, $update, { upsert => 1 } );

Updates one document that matches a filter expression and returns a MongoDB::UpdateResult or MongoDB::UnacknowledgedResult object.

The update document must have only field-update operators in it (e.g. $set).

A hash reference of options may be provided.

Valid options include:

  • arrayFilters - An array of filter documents that determines which array elements to modify for an update operation on an array field. Only available for MongoDB servers of version 3.6+.

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • upsert – defaults to false; if true, a new document will be added if one is not found by taking the filter expression and applying the update document operations to it prior to insertion.

update_many

$res = $coll->update_many( $filter, $update );
$res = $coll->update_many( $filter, $update, { upsert => 1 } );

Updates one or more documents that match a filter expression and returns a MongoDB::UpdateResult or MongoDB::UnacknowledgedResult object.

The update document must have only field-update operators in it (e.g. $set).

A hash reference of options may be provided.

Valid options include:

  • arrayFilters - An array of filter documents that determines which array elements to modify for an update operation on an array field. Only available for MongoDB servers of version 3.6+.

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • upsert – defaults to false; if true, a new document will be added if one is not found by taking the filter expression and applying the update document operations to it prior to insertion.

find

$cursor = $coll->find( $filter );
$cursor = $coll->find( $filter, $options );

$cursor = $coll->find({ i => { '$gt' => 42 } }, {limit => 20});

Executes a query with a filter expression and returns a lazy MongoDB::Cursor object. (The query is not immediately issued to the server; see below for details.)

The query can be customized using MongoDB::Cursor methods, or with an optional hash reference of options.

Valid options include:

  • allowPartialResults - get partial results from a mongos if some shards are down (instead of throwing an error).

  • batchSize – the number of documents to return per batch.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • comment – attaches a comment to the query.

  • cursorType – indicates the type of cursor to use. It must be one of three string values: 'non_tailable' (the default), 'tailable', and 'tailable_await'.

  • hintspecify an index to use; must be a string, array reference, hash reference or Tie::IxHash object.

  • limit – the maximum number of documents to return.

  • maxspecify the exclusive upper bound for a specific index.

  • maxAwaitTimeMS – the maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. This only applies to a cursorType of 'tailable_await'; the option is otherwise ignored. (Note, this will be ignored for servers before version 3.2.)

  • maxScan – (DEPRECATED) maximum number of documents or index keys to scan.

  • maxTimeMS – the maximum amount of time to allow the query to run. (Note, this will be ignored for servers before version 2.6.)

  • minspecify the inclusive lower bound for a specific index.

  • modifiers – (DEPRECATED) a hash reference of dollar-prefixed query modifiers modifying the output or behavior of a query. Top-level options will always take precedence over corresponding modifiers. Supported modifiers include $comment, $hint, $maxScan, $maxTimeMS, $max, $min, $orderby, $returnKey, $showDiskLoc, and $snapshot. Some options may not be supported by newer server versions.

  • noCursorTimeout – if true, prevents the server from timing out a cursor after a period of inactivity.

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • returnKeyOnly return the index field or fields for the results of the query.

  • showRecordId – modifies the output of a query by adding a field $recordId that uniquely identifies a document in a collection.

  • skip – the number of documents to skip before returning.

  • sort – an ordered document defining the order in which to return matching documents. See the $orderby documentation for examples.

For more information, see the Read Operations Overview in the MongoDB documentation.

Note, a MongoDB::Cursor object holds the query and does not issue the query to the server until the result method is called on it or until an iterator method like next is called. Performance will be better directly on a MongoDB::QueryResult object:

my $query_result = $coll->find( $filter )->result;

while ( my $next = $query_result->next ) {
    ...
}

find_one

$doc = $collection->find_one( $filter, $projection );
$doc = $collection->find_one( $filter, $projection, $options );

Executes a query with a filter expression and returns a single document.

If a projection argument is provided, it must be a hash reference specifying fields to return. See Limit fields to return in the MongoDB documentation for details.

If only a filter is provided or if the projection document is an empty hash reference, all fields will be returned.

my $doc = $collection->find_one( $filter );
my $doc = $collection->find_one( $filter, {}, $options );

A hash reference of options may be provided as a third argument. Valid keys include:

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • sort – an ordered document defining the order in which to return matching documents. If $orderby also exists in the modifiers document, the sort field overwrites $orderby. See docs for $orderby.

See also core documentation on querying: http://docs.mongodb.org/manual/core/read/.

find_id

$doc = $collection->find_id( $id );
$doc = $collection->find_id( $id, $projection );
$doc = $collection->find_id( $id, $projection, $options );

Executes a query with a filter expression of { _id => $id } and returns a single document.

See the find_one documentation for details on the $projection and $options parameters.

See also core documentation on querying: http://docs.mongodb.org/manual/core/read/.

find_one_and_delete

$doc = $coll->find_one_and_delete( $filter );
$doc = $coll->find_one_and_delete( $filter, $options );

Given a filter expression, this deletes a document from the database and returns it as it appeared before it was deleted.

A hash reference of options may be provided. Valid keys include:

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

find_one_and_replace

$doc = $coll->find_one_and_replace( $filter, $replacement );
$doc = $coll->find_one_and_replace( $filter, $replacement, $options );

Given a filter expression and a replacement document, this replaces a document from the database and returns it as it was either right before or right after the replacement. The default is 'before'.

The replacement document must not have any field-update operators in it (e.g. $set).

A hash reference of options may be provided. Valid keys include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • returnDocument – either the string 'before' or 'after', to indicate whether the returned document should be the one before or after replacement. The default is 'before'.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

  • upsert – defaults to false; if true, a new document will be added if one is not found

find_one_and_update

$doc = $coll->find_one_and_update( $filter, $update );
$doc = $coll->find_one_and_update( $filter, $update, $options );

Given a filter expression and a document of update operators, this updates a single document and returns it as it was either right before or right after the update. The default is 'before'.

The update document must contain only field-update operators (e.g. $set).

A hash reference of options may be provided. Valid keys include:

  • arrayFilters - An array of filter documents that determines which array elements to modify for an update operation on an array field. Only available for MongoDB servers of version 3.6+.

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • returnDocument – either the string 'before' or 'after', to indicate whether the returned document should be the one before or after replacement. The default is 'before'.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

  • upsert – defaults to false; if true, a new document will be added if one is not found

watch

Watches for changes on this collection-

Perform an aggregation with an implicit initial $changeStream stage and returns a MongoDB::ChangeStream result which can be used to iterate over the changes in the collection. This functionality is available since MongoDB 3.6.

my $stream = $collection->watch();
my $stream = $collection->watch( \@pipeline );
my $stream = $collection->watch( \@pipeline, \%options );

while (1) {

    # This inner loop will only run until no more changes are
    # available.
    while (my $change = $stream->next) {
        # process $change
    }
}

The returned stream will not block forever waiting for changes. If you want to respond to changes over a longer time use maxAwaitTimeMS and regularly call next in a loop.

Note: Using this helper method is preferred to manually aggregating with a $changeStream stage, since it will automatically resume when the connection was terminated.

The optional first argument must be an array-ref of aggregation pipeline documents. Each pipeline document must be a hash reference. Not all pipeline stages are supported after $changeStream.

The optional second argument is a hash reference with options:

  • fullDocument - The fullDocument to pass as an option to the $changeStream stage. Allowed values: default, updateLookup. Defaults to default. When set to updateLookup, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.

  • resumeAfter - The logical starting point for this change stream. This value can be obtained from the _id field of a document returned by "next" in MongoDB::ChangeStream. Cannot be specified together with startAtOperationTime

  • maxAwaitTimeMS - The maximum number of milliseconds for the server to wait before responding.

  • startAtOperationTime - A BSON::Timestamp specifying at what point in time changes will start being watched. Cannot be specified together with resumeAfter. Plain values will be coerced to BSON::Timestamp objects.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

See "aggregate" for more available options.

See the manual section on Change Streams for general usage information on change streams.

See the Change Streams specification for details on change streams.

aggregate

@pipeline = (
    { '$group' => { _id => '$state,' totalPop => { '$sum' => '$pop' } } },
    { '$match' => { totalPop => { '$gte' => 10 * 1000 * 1000 } } }
);

$result = $collection->aggregate( \@pipeline );
$result = $collection->aggregate( \@pipeline, $options );

Runs a query using the MongoDB 2.2+ aggregation framework and returns a MongoDB::QueryResult object.

The first argument must be an array-ref of aggregation pipeline documents. Each pipeline document must be a hash reference.

Note: Some pipeline documents have ordered arguments, such as $sort. Be sure to provide these argument using Tie::IxHash. E.g.:

{ '$sort' => Tie::IxHash->new( age => -1, posts => 1 ) }

A hash reference of options may be provided. Valid keys include:

  • allowDiskUse – if, true enables writing to temporary files.

  • batchSize – the number of documents to return per batch.

  • bypassDocumentValidation - skips document validation, if enabled. (Note, this will be ignored for servers before version 3.2.)

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • explain – if true, return a single document with execution information.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • hint - An index to use for this aggregation. (Only compatible with servers above version 3.6.) For more information, see the other aggregate options here: https://docs.mongodb.com/manual/reference/command/aggregate/index.html

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

Note MongoDB 2.6+ added the '$out' pipeline operator. If this operator is used to write aggregation results directly to a collection, an empty result will be returned. Create a new collection> object to query the generated result collection. When $out is used, the command is treated as a write operation and read preference is ignored.

See Aggregation in the MongoDB manual for more information on how to construct aggregation queries.

Note The use of aggregation cursors is automatic based on your server version. However, if migrating a sharded cluster from MongoDB 2.4 to 2.6 or later, you must upgrade your mongod servers first before your mongos routers or aggregation queries will fail. As a workaround, you may pass cursor => undef as an option.

count_documents

$count = $coll->count_documents( $filter );
$count = $coll->count_documents( $filter, $options );

Returns a count of documents matching a filter expression. To return a count of all documents, use an empty hash reference as the filter.

NOTE: this may result in a scan of all documents in the collection. For a fast count of the total documents in a collection see "estimated_document_count" instead.

A hash reference of options may be provided. Valid keys include:

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • hint – specify an index to use; must be a string, array reference, hash reference or Tie::IxHash object. (Requires server version 3.6 or later.)

  • limit – the maximum number of documents to count.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • skip – the number of documents to skip before counting documents.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

NOTE: When upgrading from the deprecated count method, some legacy operators are not supported and must be replaced:

+-------------+--------------------------------+
| Legacy      | Modern Replacement             |
+=============+================================+
| $where      | $expr (Requires MongoDB 3.6+)  |
+-------------+--------------------------------+
| $near       | $geoWithin with $center        |
+-------------+--------------------------------+
| $nearSphere | $geoWithin with $centerSphere  |
+-------------+--------------------------------+

estimated_document_count

$count = $coll->estimated_document_count();
$count = $coll->estimated_document_count($options);

Returns an estimated count of documents based on collection metadata.

NOTE: this method does not support sessions or transactions.

A hash reference of options may be provided. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

distinct

$result = $coll->distinct( $fieldname );
$result = $coll->distinct( $fieldname, $filter );
$result = $coll->distinct( $fieldname, $filter, $options );

Returns a MongoDB::QueryResult object that will provide distinct values for a specified field name.

The query may be limited by an optional filter expression.

A hash reference of options may be provided. Valid keys include:

  • collation - a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

See documentation for the distinct command for details.

rename

$newcollection = $collection->rename("mynewcollection");

Renames the collection. If a collection already exists with the new collection name, this method will throw an exception.

A hashref of options may be provided.

Valid options include:

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

It returns a new MongoDB::Collection object corresponding to the renamed collection.

drop

$collection->drop;

Deletes a collection as well as all of its indexes.

ordered_bulk

$bulk = $coll->ordered_bulk;
$bulk->insert_one( $doc1 );
$bulk->insert_one( $doc2 );
...
$result = $bulk->execute;

Returns a MongoDB::BulkWrite object to group write operations into fewer network round-trips. This method creates an ordered operation, where operations halt after the first error. See MongoDB::BulkWrite for more details.

The method initialize_ordered_bulk_op may be used as an alias.

A hash reference of options may be provided.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

unordered_bulk

This method works just like "ordered_bulk" except that the order that operations are sent to the database is not guaranteed and errors do not halt processing. See MongoDB::BulkWrite for more details.

The method initialize_unordered_bulk_op may be used as an alias.

A hash reference of options may be provided.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

bulk_write

$res = $coll->bulk_write( [ @requests ], $options )

This method provides syntactic sugar to construct and execute a bulk operation directly, without using initialize_ordered_bulk or initialize_unordered_bulk to generate a MongoDB::BulkWrite object and then calling methods on it. It returns a MongoDB::BulkWriteResponse object just like the MongoDB::BulkWrite execute method.

The first argument must be an array reference of requests. Requests consist of pairs of a MongoDB::Collection write method name (e.g. insert_one, delete_many) and an array reference of arguments to the corresponding method name. They may be given as pairs, or as hash or array references:

# pairs -- most efficient
@requests = (
    insert_one  => [ { x => 1 } ],
    replace_one => [ { x => 1 }, { x => 4 } ],
    delete_one  => [ { x => 4 } ],
    update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ],
);

# hash references
@requests = (
    { insert_one  => [ { x => 1 } ] },
    { replace_one => [ { x => 1 }, { x => 4 } ] },
    { delete_one  => [ { x => 4 } ] },
    { update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] },
);

# array references
@requests = (
    [ insert_one  => [ { x => 1 } ] ],
    [ replace_one => [ { x => 1 }, { x => 4 } ] ],
    [ delete_one  => [ { x => 4 } ] ],
    [ update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] ],
);

Valid method names include insert_one, insert_many, delete_one, delete_many replace_one, update_one, update_many.

An optional hash reference of options may be provided.

Valid options include:

  • bypassDocumentValidation - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

  • ordered – when true, the bulk operation is executed like "initialize_ordered_bulk". When false, the bulk operation is executed like "initialize_unordered_bulk". The default is true.

  • session - the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession

See MongoDB::BulkWrite for more details on bulk writes. Be advised that the legacy Bulk API method names differ slightly from MongoDB::Collection method names.

AUTHORS

  • David Golden <david@mongodb.com>

  • Rassi <rassi@mongodb.com>

  • Mike Friedman <friedo@friedo.com>

  • Kristina Chodorow <k.chodorow@gmail.com>

  • Florian Ragwitz <rafl@debian.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2020 by MongoDB, Inc.

This is free software, licensed under:

The Apache License, Version 2.0, January 2004