File Coverage

blib/lib/MongoDB/Collection.pm
Criterion Covered Total %
statement 108 386 27.9
branch 0 174 0.0
condition 0 118 0.0
subroutine 36 71 50.7
pod 23 27 85.1
total 167 776 21.5


line stmt bran cond sub pod time code
1             # Copyright 2009 - present MongoDB, Inc.
2             #
3             # Licensed under the Apache License, Version 2.0 (the "License");
4             # you may not use this file except in compliance with the License.
5             # You may obtain a copy of the License at
6             #
7             # http://www.apache.org/licenses/LICENSE-2.0
8             #
9             # Unless required by applicable law or agreed to in writing, software
10             # distributed under the License is distributed on an "AS IS" BASIS,
11             # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12             # See the License for the specific language governing permissions and
13             # limitations under the License.
14              
15 59     59   373 use strict;
  59         118  
  59         1743  
16 59     59   280 use warnings;
  59         107  
  59         1965  
17             package MongoDB::Collection;
18              
19              
20             # ABSTRACT: A MongoDB Collection
21              
22 59     59   286 use version;
  59         113  
  59         394  
23             our $VERSION = 'v2.2.2';
24              
25 59     59   25405 use MongoDB::ChangeStream;
  59         216  
  59         2335  
26 59     59   466 use MongoDB::Error;
  59         116  
  59         6103  
27 59     59   29444 use MongoDB::IndexView;
  59         188  
  59         1946  
28 59     59   427 use MongoDB::InsertManyResult;
  59         117  
  59         1164  
29 59     59   264 use MongoDB::QueryResult;
  59         117  
  59         1028  
30 59     59   261 use MongoDB::WriteConcern;
  59         120  
  59         978  
31 59     59   27121 use MongoDB::Op::_Aggregate;
  59         221  
  59         2141  
32 59     59   448 use MongoDB::Op::_BatchInsert;
  59         126  
  59         1514  
33 59     59   27704 use MongoDB::Op::_BulkWrite;
  59         190  
  59         2370  
34 59     59   27646 use MongoDB::Op::_Count;
  59         198  
  59         1948  
35 59     59   436 use MongoDB::Op::_CreateIndexes;
  59         135  
  59         1211  
36 59     59   296 use MongoDB::Op::_Delete;
  59         133  
  59         1747  
37 59     59   24271 use MongoDB::Op::_Distinct;
  59         189  
  59         2044  
38 59     59   23836 use MongoDB::Op::_DropCollection;
  59         189  
  59         1880  
39 59     59   22998 use MongoDB::Op::_FindAndDelete;
  59         180  
  59         1898  
40 59     59   29732 use MongoDB::Op::_FindAndUpdate;
  59         198  
  59         2080  
41 59     59   462 use MongoDB::Op::_InsertOne;
  59         120  
  59         1204  
42 59     59   24820 use MongoDB::Op::_ListIndexes;
  59         197  
  59         1967  
43 59     59   25640 use MongoDB::Op::_ParallelScan;
  59         195  
  59         3056  
44 59     59   31446 use MongoDB::Op::_RenameCollection;
  59         184  
  59         2096  
45 59     59   439 use MongoDB::Op::_Query;
  59         114  
  59         1573  
46 59     59   299 use MongoDB::Op::_Update;
  59         131  
  59         1678  
47 59         476 use MongoDB::_Types qw(
48             BSONCodec
49             NonNegNum
50             ReadPreference
51             ReadConcern
52             WriteConcern
53 59     59   332 );
  59         120  
54 59         252 use Types::Standard qw(
55             HashRef
56             InstanceOf
57             Str
58 59     59   84446 );
  59         124  
59 59     59   49146 use Tie::IxHash;
  59         126  
  59         1276  
60 59     59   275 use Carp 'carp';
  59         127  
  59         3056  
61 59     59   322 use boolean;
  59         114  
  59         493  
62 59     59   3251 use Safe::Isa;
  59         123  
  59         7497  
63 59     59   378 use Scalar::Util qw/blessed reftype/;
  59         109  
  59         2364  
64 59     59   299 use Moo;
  59         114  
  59         278  
65 59     59   19105 use namespace::clean -except => 'meta';
  59         129  
  59         312  
66              
67             #--------------------------------------------------------------------------#
68             # constructor attributes
69             #--------------------------------------------------------------------------#
70              
71             #pod =attr database
72             #pod
73             #pod The L representing the database that contains
74             #pod the collection.
75             #pod
76             #pod =cut
77              
78             has database => (
79             is => 'ro',
80             isa => InstanceOf['MongoDB::Database'],
81             required => 1,
82             );
83              
84             #pod =attr name
85             #pod
86             #pod The name of the collection.
87             #pod
88             #pod =cut
89              
90             has name => (
91             is => 'ro',
92             isa => Str,
93             required => 1,
94             );
95              
96             #pod =attr read_preference
97             #pod
98             #pod A L object. It may be initialized with a string
99             #pod corresponding to one of the valid read preference modes or a hash reference
100             #pod that will be coerced into a new MongoDB::ReadPreference object.
101             #pod By default it will be inherited from a L object.
102             #pod
103             #pod =cut
104              
105             has read_preference => (
106             is => 'ro',
107             isa => ReadPreference,
108             required => 1,
109             coerce => ReadPreference->coercion,
110             );
111              
112             #pod =attr write_concern
113             #pod
114             #pod A L object. It may be initialized with a hash
115             #pod reference that will be coerced into a new MongoDB::WriteConcern object.
116             #pod By default it will be inherited from a L object.
117             #pod
118             #pod =cut
119              
120             has write_concern => (
121             is => 'ro',
122             isa => WriteConcern,
123             required => 1,
124             coerce => WriteConcern->coercion,
125             );
126              
127             #pod =attr read_concern
128             #pod
129             #pod A L object. May be initialized with a hash
130             #pod reference or a string that will be coerced into the level of read
131             #pod concern.
132             #pod
133             #pod By default it will be inherited from a L object.
134             #pod
135             #pod =cut
136              
137             has read_concern => (
138             is => 'ro',
139             isa => ReadConcern,
140             required => 1,
141             coerce => ReadConcern->coercion,
142             );
143              
144             #pod =attr max_time_ms
145             #pod
146             #pod Specifies the default maximum amount of time in milliseconds that the
147             #pod server should use for working on a query.
148             #pod
149             #pod B: this will only be used for server versions 2.6 or greater, as that
150             #pod was when the C<$maxTimeMS> meta-operator was introduced.
151             #pod
152             #pod =cut
153              
154             has max_time_ms => (
155             is => 'ro',
156             isa => NonNegNum,
157             required => 1,
158             );
159              
160             #pod =attr bson_codec
161             #pod
162             #pod An object that provides the C and C methods, such
163             #pod as from L. It may be initialized with a hash reference that
164             #pod will be coerced into a new L object. By default it will be
165             #pod inherited from a L object.
166             #pod
167             #pod =cut
168              
169             has bson_codec => (
170             is => 'ro',
171             isa => BSONCodec,
172             coerce => BSONCodec->coercion,
173             required => 1,
174             );
175              
176             #--------------------------------------------------------------------------#
177             # computed attributes
178             #--------------------------------------------------------------------------#
179              
180             #pod =method client
181             #pod
182             #pod $client = $coll->client;
183             #pod
184             #pod Returns the L object associated with this
185             #pod object.
186             #pod
187             #pod =cut
188              
189             has _client => (
190             is => 'lazy',
191             isa => InstanceOf['MongoDB::MongoClient'],
192             reader => 'client',
193             init_arg => undef,
194             builder => '_build__client',
195             );
196              
197             sub _build__client {
198 0     0     my ($self) = @_;
199 0           return $self->database->_client;
200             }
201              
202             #pod =method full_name
203             #pod
204             #pod $full_name = $coll->full_name;
205             #pod
206             #pod Returns the full name of the collection, including the namespace of the
207             #pod database it's in prefixed with a dot character. E.g. collection "foo" in
208             #pod database "test" would result in a C of "test.foo".
209             #pod
210             #pod =cut
211              
212             has _full_name => (
213             is => 'lazy',
214             isa => Str,
215             reader => 'full_name',
216             init_arg => undef,
217             builder => '_build__full_name',
218             );
219              
220             sub _build__full_name {
221 0     0     my ($self) = @_;
222 0           my $name = $self->name;
223 0           my $db_name = $self->database->name;
224 0           return "${db_name}.${name}";
225             }
226              
227             #pod =method indexes
228             #pod
229             #pod $indexes = $collection->indexes;
230             #pod
231             #pod $collection->indexes->create_one( [ x => 1 ], { unique => 1 } );
232             #pod $collection->indexes->drop_all;
233             #pod
234             #pod Returns a L object for managing the indexes associated
235             #pod with the collection.
236             #pod
237             #pod =cut
238              
239             has _indexes => (
240             is => 'lazy',
241             isa => InstanceOf['MongoDB::IndexView'],
242             reader => 'indexes',
243             init_arg => undef,
244             builder => '_build__indexes',
245             );
246              
247             sub _build__indexes {
248 0     0     my ($self) = @_;
249 0           return MongoDB::IndexView->new( collection => $self );
250             }
251              
252             # these are constant, so we cache them
253             has _op_args => (
254             is => 'lazy',
255             isa => HashRef,
256             init_arg => undef,
257             builder => '_build__op_args',
258             );
259              
260             sub _build__op_args {
261 0     0     my ($self) = @_;
262             return {
263 0           client => $self->client,
264             db_name => $self->database->name,
265             bson_codec => $self->bson_codec,
266             coll_name => $self->name,
267             write_concern => $self->write_concern,
268             read_concern => $self->read_concern,
269             read_preference => $self->read_preference,
270             full_name => join( ".", $self->database->name, $self->name ),
271             monitoring_callback => $self->client->monitoring_callback,
272             };
273             }
274              
275             with $_ for qw(
276             MongoDB::Role::_DeprecationWarner
277             );
278              
279             #--------------------------------------------------------------------------#
280             # public methods
281             #--------------------------------------------------------------------------#
282              
283             #pod =method clone
284             #pod
285             #pod $coll2 = $coll1->clone( write_concern => { w => 2 } );
286             #pod
287             #pod Constructs a copy of the original collection, but allows changing
288             #pod attributes in the copy.
289             #pod
290             #pod =cut
291              
292             sub clone {
293 0     0 1   my ($self, @args) = @_;
294 0           my $class = ref($self);
295 0 0 0       if ( @args == 1 && ref( $args[0] ) eq 'HASH' ) {
296 0           return $class->new( %$self, %{$args[0]} );
  0            
297             }
298              
299 0           return $class->new( %$self, @args );
300             }
301              
302             #pod =method with_codec
303             #pod
304             #pod $coll2 = $coll1->with_codec( $new_codec );
305             #pod $coll2 = $coll1->with_codec( prefer_numeric => 1 );
306             #pod
307             #pod Constructs a copy of the original collection, but clones the C.
308             #pod If given an object that does C and C, it is
309             #pod equivalent to:
310             #pod
311             #pod $coll2 = $coll1->clone( bson_codec => $new_codec );
312             #pod
313             #pod If given a hash reference or a list of key/value pairs, it is equivalent
314             #pod to:
315             #pod
316             #pod $coll2 = $coll1->clone(
317             #pod bson_codec => $coll1->bson_codec->clone( @list )
318             #pod );
319             #pod
320             #pod =cut
321              
322             sub with_codec {
323 0     0 1   my ( $self, @args ) = @_;
324 0 0         if ( @args == 1 ) {
    0          
325 0           my $arg = $args[0];
326 0 0         if ( eval { $arg->can('encode_bson') && $arg->can('decode_bson') } ) {
  0 0          
    0          
327 0           return $self->clone( bson_codec => $arg );
328             }
329             elsif ( ref $arg eq 'HASH' ) {
330 0           return $self->clone( bson_codec => $self->bson_codec->clone(%$arg) );
331             }
332             }
333             elsif ( @args % 2 == 0 ) {
334 0           return $self->clone( bson_codec => $self->bson_codec->clone(@args) );
335             }
336              
337             # fallthrough is argument error
338             MongoDB::UsageError->throw(
339 0           "argument to with_codec must be new codec, hashref or key/value pairs" );
340             }
341              
342             #pod =method insert_one
343             #pod
344             #pod $res = $coll->insert_one( $document );
345             #pod $res = $coll->insert_one( $document, $options );
346             #pod $id = $res->inserted_id;
347             #pod
348             #pod Inserts a single L into the database and returns a
349             #pod L or L object.
350             #pod
351             #pod If no C<_id> field is present, one will be added when a document is
352             #pod serialized for the database without modifying the original document.
353             #pod The generated C<_id> may be retrieved from the result object.
354             #pod
355             #pod An optional hash reference of options may be given.
356             #pod
357             #pod Valid options include:
358             #pod
359             #pod =for :list
360             #pod * C - skips document validation, if enabled; this
361             #pod is ignored for MongoDB servers older than version 3.2.
362             #pod * C - the session to use for these operations. If not supplied, will
363             #pod use an implicit session. For more information see L
364             #pod
365             #pod =cut
366              
367             # args not unpacked for efficiency; args are self, document
368             sub insert_one {
369 0 0   0 1   MongoDB::UsageError->throw("document argument must be a reference")
370             unless ref( $_[1] );
371              
372             return $_[0]->client->send_retryable_write_op(
373             MongoDB::Op::_InsertOne->_new(
374             session => $_[0]->client->_get_session_from_hashref( $_[2] ),
375 0           ( defined $_[2] ? (%{$_[2]}) : () ),
376             document => $_[1],
377 0 0         %{ $_[0]->_op_args },
  0            
378             )
379             );
380             }
381              
382             #pod =method insert_many
383             #pod
384             #pod $res = $coll->insert_many( [ @documents ] );
385             #pod $res = $coll->insert_many( [ @documents ], { ordered => 0 } );
386             #pod
387             #pod Inserts each of the L in an array reference into the
388             #pod database and returns a L or
389             #pod L. This is syntactic sugar for doing a
390             #pod L operation.
391             #pod
392             #pod If no C<_id> field is present, one will be added when a document is
393             #pod serialized for the database without modifying the original document.
394             #pod The generated C<_id> may be retrieved from the result object.
395             #pod
396             #pod An optional hash reference of options may be provided.
397             #pod
398             #pod Valid options include:
399             #pod
400             #pod =for :list
401             #pod * C - skips document validation, if enabled; this
402             #pod is ignored for MongoDB servers older than version 3.2.
403             #pod * C - the session to use for these operations. If not supplied, will
404             #pod use an implicit session. For more information see L
405             #pod * C – when true, the server will halt insertions after the first
406             #pod error (if any). When false, all documents will be processed and any
407             #pod error will only be thrown after all insertions are attempted. The
408             #pod default is true.
409             #pod
410             #pod On MongoDB servers before version 2.6, C bulk operations are
411             #pod emulated with individual inserts to capture error information. On 2.6 or
412             #pod later, this method will be significantly faster than individual C
413             #pod calls.
414             #pod
415             #pod =cut
416              
417             # args not unpacked for efficiency; args are self, document, options
418             sub insert_many {
419 0 0   0 1   MongoDB::UsageError->throw("documents argument must be an array reference")
420             unless ref( $_[1] ) eq 'ARRAY';
421              
422             my $op = MongoDB::Op::_BulkWrite->_new(
423             # default
424             ordered => 1,
425             # user overrides
426             session => $_[0]->client->_get_session_from_hashref( $_[2] ),
427 0           ( defined $_[2] ? ( %{ $_[2] } ) : () ),
428             # un-overridable
429 0           queue => [ map { [ insert => $_ ] } @{ $_[1] } ],
  0            
430             # insert_many is specifically retryable (PERL-792)
431             _retryable => 1,
432 0 0         %{ $_[0]->_op_args },
  0            
433             );
434              
435             # internally ends up performing a retryable write if possible, see OP::_BulkWrite
436 0           my $res = $_[0]->client->send_write_op( $op );
437              
438 0 0         return $op->_should_use_acknowledged_write
439             ? MongoDB::InsertManyResult->_new(
440             acknowledged => 1,
441             inserted => $res->inserted,
442             write_errors => [],
443             write_concern_errors => [],
444             )
445             : MongoDB::UnacknowledgedResult->_new(
446             write_errors => [],
447             write_concern_errors => [],
448             );
449             }
450              
451             #pod =method delete_one
452             #pod
453             #pod $res = $coll->delete_one( $filter );
454             #pod $res = $coll->delete_one( { _id => $id } );
455             #pod $res = $coll->delete_one( $filter, { collation => { locale => "en_US" } } );
456             #pod
457             #pod Deletes a single document that matches a L and returns a
458             #pod L or L object.
459             #pod
460             #pod A hash reference of options may be provided.
461             #pod
462             #pod Valid options include:
463             #pod
464             #pod =for :list
465             #pod * C - a L defining the collation for this operation.
466             #pod See docs for the format of the collation document here:
467             #pod L.
468             #pod * C - the session to use for these operations. If not supplied, will
469             #pod use an implicit session. For more information see L
470             #pod
471             #pod =cut
472              
473             # args not unpacked for efficiency; args are self, filter, options
474             sub delete_one {
475 0 0   0 1   MongoDB::UsageError->throw("filter argument must be a reference")
476             unless ref( $_[1] );
477              
478             return $_[0]->client->send_retryable_write_op(
479             MongoDB::Op::_Delete->_new(
480             session => $_[0]->client->_get_session_from_hashref( $_[2] ),
481 0           ( defined $_[2] ? (%{$_[2]}) : () ),
482             filter => $_[1],
483             just_one => 1,
484 0 0         %{ $_[0]->_op_args },
  0            
485             )
486             );
487             }
488              
489             #pod =method delete_many
490             #pod
491             #pod $res = $coll->delete_many( $filter );
492             #pod $res = $coll->delete_many( { name => "Larry" } );
493             #pod $res = $coll->delete_many( $filter, { collation => { locale => "en_US" } } );
494             #pod
495             #pod Deletes all documents that match a L
496             #pod and returns a L or L
497             #pod object.
498             #pod
499             #pod Valid options include:
500             #pod
501             #pod =for :list
502             #pod * C - a L defining the collation for this operation.
503             #pod See docs for the format of the collation document here:
504             #pod L.
505             #pod * C - the session to use for these operations. If not supplied, will
506             #pod use an implicit session. For more information see L
507             #pod
508             #pod =cut
509              
510             # args not unpacked for efficiency; args are self, filter, options
511             sub delete_many {
512 0 0   0 1   MongoDB::UsageError->throw("filter argument must be a reference")
513             unless ref( $_[1] );
514              
515             return $_[0]->client->send_write_op(
516             MongoDB::Op::_Delete->_new(
517             session => $_[0]->client->_get_session_from_hashref( $_[2] ),
518 0           ( defined $_[2] ? (%{$_[2]}) : () ),
519             filter => $_[1],
520             just_one => 0,
521 0 0         %{ $_[0]->_op_args },
  0            
522             )
523             );
524             }
525              
526             #pod =method replace_one
527             #pod
528             #pod $res = $coll->replace_one( $filter, $replacement );
529             #pod $res = $coll->replace_one( $filter, $replacement, { upsert => 1 } );
530             #pod
531             #pod Replaces one document that matches a L
532             #pod expression> and returns a L or
533             #pod L object.
534             #pod
535             #pod The replacement document must not have any field-update operators in it (e.g.
536             #pod C<$set>).
537             #pod
538             #pod A hash reference of options may be provided.
539             #pod
540             #pod Valid options include:
541             #pod
542             #pod =for :list
543             #pod * C - skips document validation, if enabled; this
544             #pod is ignored for MongoDB servers older than version 3.2.
545             #pod * C - a L defining the collation for this operation.
546             #pod See docs for the format of the collation document here:
547             #pod L.
548             #pod * C - the session to use for these operations. If not supplied, will
549             #pod use an implicit session. For more information see L
550             #pod * C – defaults to false; if true, a new document will be added if one
551             #pod is not found
552             #pod
553             #pod =cut
554              
555             # args not unpacked for efficiency; args are self, filter, update, options
556             sub replace_one {
557 0 0 0 0 1   MongoDB::UsageError->throw("filter and replace arguments must be references")
558             unless ref( $_[1] ) && ref( $_[2] );
559              
560             return $_[0]->client->send_retryable_write_op(
561             MongoDB::Op::_Update->_new(
562             session => $_[0]->client->_get_session_from_hashref( $_[3] ),
563 0           ( defined $_[3] ? (%{$_[3]}) : () ),
564             filter => $_[1],
565             update => $_[2],
566             multi => false,
567             is_replace => 1,
568 0 0         %{ $_[0]->_op_args },
  0            
569             )
570             );
571             }
572              
573             #pod =method update_one
574             #pod
575             #pod $res = $coll->update_one( $filter, $update );
576             #pod $res = $coll->update_one( $filter, $update, { upsert => 1 } );
577             #pod
578             #pod Updates one document that matches a L
579             #pod and returns a L or L
580             #pod object.
581             #pod
582             #pod The update document must have only field-update operators in it (e.g.
583             #pod C<$set>).
584             #pod
585             #pod A hash reference of options may be provided.
586             #pod
587             #pod Valid options include:
588             #pod
589             #pod =for :list
590             #pod * C - An array of filter documents that determines which array
591             #pod elements to modify for an update operation on an array field. Only available
592             #pod for MongoDB servers of version 3.6+.
593             #pod * C - skips document validation, if enabled; this
594             #pod is ignored for MongoDB servers older than version 3.2.
595             #pod * C - a L defining the collation for this operation.
596             #pod See docs for the format of the collation document here:
597             #pod L.
598             #pod * C - the session to use for these operations. If not supplied, will
599             #pod use an implicit session. For more information see L
600             #pod * C – defaults to false; if true, a new document will be added if
601             #pod one is not found by taking the filter expression and applying the update
602             #pod document operations to it prior to insertion.
603             #pod
604             #pod =cut
605              
606             # args not unpacked for efficiency; args are self, filter, update, options
607             sub update_one {
608 0 0 0 0 1   MongoDB::UsageError->throw("filter and update arguments must be references")
609             unless ref( $_[1] ) && ref( $_[2] );
610              
611             return $_[0]->client->send_retryable_write_op(
612             MongoDB::Op::_Update->_new(
613             session => $_[0]->client->_get_session_from_hashref( $_[3] ),
614 0           ( defined $_[3] ? (%{$_[3]}) : () ),
615             filter => $_[1],
616             update => $_[2],
617             multi => false,
618             is_replace => 0,
619 0 0         %{ $_[0]->_op_args },
  0            
620             )
621             );
622             }
623              
624             #pod =method update_many
625             #pod
626             #pod $res = $coll->update_many( $filter, $update );
627             #pod $res = $coll->update_many( $filter, $update, { upsert => 1 } );
628             #pod
629             #pod Updates one or more documents that match a L
630             #pod expression> and returns a L or
631             #pod L object.
632             #pod
633             #pod The update document must have only field-update operators in it (e.g.
634             #pod C<$set>).
635             #pod
636             #pod A hash reference of options may be provided.
637             #pod
638             #pod Valid options include:
639             #pod
640             #pod =for :list
641             #pod * C - An array of filter documents that determines which array
642             #pod elements to modify for an update operation on an array field. Only available
643             #pod for MongoDB servers of version 3.6+.
644             #pod * C - skips document validation, if enabled; this
645             #pod is ignored for MongoDB servers older than version 3.2.
646             #pod * C - a L defining the collation for this operation.
647             #pod See docs for the format of the collation document here:
648             #pod L.
649             #pod * C - the session to use for these operations. If not supplied, will
650             #pod use an implicit session. For more information see L
651             #pod * C – defaults to false; if true, a new document will be added if
652             #pod one is not found by taking the filter expression and applying the update
653             #pod document operations to it prior to insertion.
654             #pod
655             #pod =cut
656              
657             # args not unpacked for efficiency; args are self, filter, update, options
658             sub update_many {
659 0 0 0 0 1   MongoDB::UsageError->throw("filter and update arguments must be references")
660             unless ref( $_[1] ) && ref( $_[2] );
661              
662             return $_[0]->client->send_write_op(
663             MongoDB::Op::_Update->_new(
664             session => $_[0]->client->_get_session_from_hashref( $_[3] ),
665 0           ( defined $_[3] ? (%{$_[3]}) : () ),
666             filter => $_[1],
667             update => $_[2],
668             multi => true,
669             is_replace => 0,
670 0 0         %{ $_[0]->_op_args },
  0            
671             )
672             );
673             }
674              
675             #pod =method find
676             #pod
677             #pod $cursor = $coll->find( $filter );
678             #pod $cursor = $coll->find( $filter, $options );
679             #pod
680             #pod $cursor = $coll->find({ i => { '$gt' => 42 } }, {limit => 20});
681             #pod
682             #pod Executes a query with a L and returns a
683             #pod B C object. (The query is not immediately
684             #pod issued to the server; see below for details.)
685             #pod
686             #pod The query can be customized using L methods, or with an
687             #pod optional hash reference of options.
688             #pod
689             #pod Valid options include:
690             #pod
691             #pod =for :list
692             #pod * C - get partial results from a mongos if some shards are
693             #pod down (instead of throwing an error).
694             #pod * C – the number of documents to return per batch.
695             #pod * C - a L defining the collation for this operation.
696             #pod See docs for the format of the collation document here:
697             #pod L.
698             #pod * C – attaches a comment to the query.
699             #pod * C – indicates the type of cursor to use. It must be one of three
700             #pod string values: C<'non_tailable'> (the default), C<'tailable'>, and
701             #pod C<'tailable_await'>.
702             #pod * C – L
703             #pod use|http://docs.mongodb.org/manual/reference/command/count/#specify-the-index-to-use>;
704             #pod must be a string, array reference, hash reference or L object.
705             #pod * C – the maximum number of documents to return.
706             #pod * C – L upper bound for a specific index|
707             #pod https://docs.mongodb.com/manual/reference/operator/meta/max/>.
708             #pod * C – the maximum amount of time for the server to wait on
709             #pod new documents to satisfy a tailable cursor query. This only applies
710             #pod to a C of 'tailable_await'; the option is otherwise ignored.
711             #pod (Note, this will be ignored for servers before version 3.2.)
712             #pod * C – (DEPRECATED) L
713             #pod https://docs.mongodb.com/manual/reference/operator/meta/maxScan/>.
714             #pod * C – the maximum amount of time to allow the query to run.
715             #pod (Note, this will be ignored for servers before version 2.6.)
716             #pod * C – L lower bound for a specific index|
717             #pod https://docs.mongodb.com/manual/reference/operator/meta/min/>.
718             #pod * C – (DEPRECATED) a hash reference of dollar-prefixed L
719             #pod modifiers|http://docs.mongodb.org/manual/reference/operator/query-modifier/>
720             #pod modifying the output or behavior of a query. Top-level options will always
721             #pod take precedence over corresponding modifiers. Supported modifiers include
722             #pod $comment, $hint, $maxScan, $maxTimeMS, $max, $min, $orderby, $returnKey,
723             #pod $showDiskLoc, and $snapshot. Some options may not be supported by
724             #pod newer server versions.
725             #pod * C – if true, prevents the server from timing out a cursor
726             #pod after a period of inactivity.
727             #pod * C - a hash reference defining fields to return. See "L
728             #pod fields to return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>"
729             #pod in the MongoDB documentation for details.
730             #pod * C - the session to use for these operations. If not supplied, will
731             #pod use an implicit session. For more information see L
732             #pod * C – L
733             #pod the query|https://docs.mongodb.com/manual/reference/operator/meta/returnKey/>.
734             #pod * C – modifies the output of a query by adding a field
735             #pod L<$recordId|https://docs.mongodb.com/manual/reference/method/cursor.showRecordId/>
736             #pod that uniquely identifies a document in a collection.
737             #pod * C – the number of documents to skip before returning.
738             #pod * C – an L defining the order in which
739             #pod to return matching documents. See the L<$orderby
740             #pod documentation|https://docs.mongodb.com/manual/reference/operator/meta/orderby/>
741             #pod for examples.
742             #pod
743             #pod For more information, see the L
744             #pod Overview|http://docs.mongodb.org/manual/core/read-operations-introduction/> in
745             #pod the MongoDB documentation.
746             #pod
747             #pod B, a L object holds the query and does not issue the
748             #pod query to the server until the L method is
749             #pod called on it or until an iterator method like L
750             #pod is called. Performance will be better directly on a
751             #pod L object:
752             #pod
753             #pod my $query_result = $coll->find( $filter )->result;
754             #pod
755             #pod while ( my $next = $query_result->next ) {
756             #pod ...
757             #pod }
758             #pod
759             #pod =cut
760              
761             sub find {
762 0     0 1   my ( $self, $filter, $options ) = @_;
763 0   0       $options ||= {};
764              
765             # backwards compatible sort option for deprecated 'query' alias
766 0 0         $options->{sort} = delete $options->{sort_by} if $options->{sort_by};
767              
768             # possibly fallback to default maxTimeMS
769 0 0 0       if ( !exists $options->{maxTimeMS} && $self->max_time_ms ) {
770 0           $options->{maxTimeMS} = $self->max_time_ms;
771             }
772              
773 0           my $session = $self->client->_get_session_from_hashref( $options );
774              
775             # coerce to IxHash
776 0           __ixhash( $options, 'sort' );
777              
778             return MongoDB::Cursor->new(
779             client => $self->{_client},
780             query => MongoDB::Op::_Query->_new(
781             filter => $filter || {},
782             options => MongoDB::Op::_Query->precondition_options($options),
783             session => $session,
784 0   0       %{ $self->_op_args },
  0            
785             )
786             );
787             }
788              
789             #pod =method find_one
790             #pod
791             #pod $doc = $collection->find_one( $filter, $projection );
792             #pod $doc = $collection->find_one( $filter, $projection, $options );
793             #pod
794             #pod Executes a query with a L and returns a
795             #pod single document.
796             #pod
797             #pod If a projection argument is provided, it must be a hash reference specifying
798             #pod fields to return. See L
799             #pod return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>
800             #pod in the MongoDB documentation for details.
801             #pod
802             #pod If only a filter is provided or if the projection document is an empty hash
803             #pod reference, all fields will be returned.
804             #pod
805             #pod my $doc = $collection->find_one( $filter );
806             #pod my $doc = $collection->find_one( $filter, {}, $options );
807             #pod
808             #pod A hash reference of options may be provided as a third argument. Valid keys
809             #pod include:
810             #pod
811             #pod =for :list
812             #pod * C - a L defining the collation for this operation.
813             #pod See docs for the format of the collation document here:
814             #pod L.
815             #pod * C – the maximum amount of time in milliseconds to allow the
816             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
817             #pod * C - the session to use for these operations. If not supplied, will
818             #pod use an implicit session. For more information see L
819             #pod * C – an L defining the order in which
820             #pod to return matching documents. If C<$orderby> also exists in the modifiers
821             #pod document, the sort field overwrites C<$orderby>. See docs for
822             #pod L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
823             #pod
824             #pod See also core documentation on querying:
825             #pod L.
826             #pod
827             #pod =cut
828              
829             sub find_one {
830 0     0 1   my ( $self, $filter, $projection, $options ) = @_;
831 0   0       $options ||= {};
832              
833             # possibly fallback to default maxTimeMS
834 0 0 0       if ( !exists $options->{maxTimeMS} && $self->max_time_ms ) {
835 0           $options->{maxTimeMS} = $self->max_time_ms;
836             }
837              
838 0           my $session = $self->client->_get_session_from_hashref( $options );
839              
840             # coerce to IxHash
841 0           __ixhash( $options, 'sort' );
842             # overide projection and limit
843 0           $options->{projection} = $projection;
844 0           $options->{limit} = -1;
845              
846             return $self->client->send_retryable_read_op(
847             MongoDB::Op::_Query->_new(
848             filter => $filter || {},
849             options => MongoDB::Op::_Query->precondition_options($options),
850             session => $session,
851 0   0       %{ $self->_op_args },
  0            
852             )
853             )->next;
854             }
855              
856             #pod =method find_id
857             #pod
858             #pod $doc = $collection->find_id( $id );
859             #pod $doc = $collection->find_id( $id, $projection );
860             #pod $doc = $collection->find_id( $id, $projection, $options );
861             #pod
862             #pod Executes a query with a L of C<< { _id
863             #pod => $id } >> and returns a single document.
864             #pod
865             #pod See the L documentation for details on the $projection and $options parameters.
866             #pod
867             #pod See also core documentation on querying:
868             #pod L.
869             #pod
870             #pod =cut
871              
872             sub find_id {
873 0     0 1   my $self = shift;
874 0           my $id = shift;
875 0           return $self->find_one({ _id => $id }, @_);
876             }
877              
878             #pod =method find_one_and_delete
879             #pod
880             #pod $doc = $coll->find_one_and_delete( $filter );
881             #pod $doc = $coll->find_one_and_delete( $filter, $options );
882             #pod
883             #pod Given a L, this deletes a document from
884             #pod the database and returns it as it appeared before it was deleted.
885             #pod
886             #pod A hash reference of options may be provided. Valid keys include:
887             #pod
888             #pod =for :list
889             #pod * C - a L defining the collation for this operation.
890             #pod See docs for the format of the collation document here:
891             #pod L.
892             #pod * C – the maximum amount of time in milliseconds to allow the
893             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
894             #pod * C - a hash reference defining fields to return. See "L
895             #pod fields to
896             #pod return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>"
897             #pod in the MongoDB documentation for details.
898             #pod * C - the session to use for these operations. If not supplied, will
899             #pod use an implicit session. For more information see L
900             #pod * C – an L defining the order in
901             #pod which to return matching documents. See docs for
902             #pod L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
903             #pod
904             #pod =cut
905              
906             sub find_one_and_delete {
907 0 0   0 1   MongoDB::UsageError->throw("filter argument must be a reference")
908             unless ref( $_[1] );
909              
910 0           my ( $self, $filter, $options ) = @_;
911 0   0       $options ||= {};
912              
913             # rename projection -> fields
914 0 0         $options->{fields} = delete $options->{projection} if exists $options->{projection};
915              
916             # possibly fallback to default maxTimeMS
917 0 0 0       if ( ! exists $options->{maxTimeMS} && $self->max_time_ms ) {
918 0           $options->{maxTimeMS} = $self->max_time_ms;
919             }
920              
921 0           my $session = $self->client->_get_session_from_hashref( $options );
922              
923             # coerce to IxHash
924 0           __ixhash($options, 'sort');
925              
926             my $op = MongoDB::Op::_FindAndDelete->_new(
927 0           %{ $_[0]->_op_args },
  0            
928             filter => $filter,
929             options => $options,
930             session => $session,
931             );
932              
933 0 0         return $op->_should_use_acknowledged_write
934             ? $self->client->send_retryable_write_op( $op )
935             : $self->client->send_write_op( $op );
936             }
937              
938             #pod =method find_one_and_replace
939             #pod
940             #pod $doc = $coll->find_one_and_replace( $filter, $replacement );
941             #pod $doc = $coll->find_one_and_replace( $filter, $replacement, $options );
942             #pod
943             #pod Given a L and a replacement document,
944             #pod this replaces a document from the database and returns it as it was either
945             #pod right before or right after the replacement. The default is 'before'.
946             #pod
947             #pod The replacement document must not have any field-update operators in it (e.g.
948             #pod C<$set>).
949             #pod
950             #pod A hash reference of options may be provided. Valid keys include:
951             #pod
952             #pod =for :list
953             #pod * C - skips document validation, if enabled; this
954             #pod is ignored for MongoDB servers older than version 3.2.
955             #pod * C - a L defining the collation for this operation.
956             #pod See docs for the format of the collation document here:
957             #pod L.
958             #pod * C – the maximum amount of time in milliseconds to allow the
959             #pod command to run.
960             #pod * C - a hash reference defining fields to return. See "L
961             #pod fields to
962             #pod return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>"
963             #pod in the MongoDB documentation for details.
964             #pod * C – either the string C<'before'> or C<'after'>, to indicate
965             #pod whether the returned document should be the one before or after replacement.
966             #pod The default is C<'before'>.
967             #pod * C - the session to use for these operations. If not supplied, will
968             #pod use an implicit session. For more information see L
969             #pod * C – an L defining the order in
970             #pod which to return matching documents. See docs for
971             #pod L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
972             #pod * C – defaults to false; if true, a new document will be added if one
973             #pod is not found
974             #pod
975             #pod =cut
976              
977             sub find_one_and_replace {
978 0 0 0 0 1   MongoDB::UsageError->throw("filter and replace arguments must be references")
979             unless ref( $_[1] ) && ref( $_[2] );
980              
981 0           my ( $self, $filter, $replacement, $options ) = @_;
982 0           $options->{is_replace} = 1;
983 0           return $self->_find_one_and_update_or_replace($filter, $replacement, $options);
984             }
985              
986             #pod =method find_one_and_update
987             #pod
988             #pod $doc = $coll->find_one_and_update( $filter, $update );
989             #pod $doc = $coll->find_one_and_update( $filter, $update, $options );
990             #pod
991             #pod Given a L and a document of update
992             #pod operators, this updates a single document and returns it as it was either right
993             #pod before or right after the update. The default is 'before'.
994             #pod
995             #pod The update document must contain only field-update operators (e.g. C<$set>).
996             #pod
997             #pod A hash reference of options may be provided. Valid keys include:
998             #pod
999             #pod =for :list
1000             #pod * C - An array of filter documents that determines which array
1001             #pod elements to modify for an update operation on an array field. Only available
1002             #pod for MongoDB servers of version 3.6+.
1003             #pod * C - skips document validation, if enabled; this
1004             #pod is ignored for MongoDB servers older than version 3.2.
1005             #pod * C - a L defining the collation for this operation.
1006             #pod See docs for the format of the collation document here:
1007             #pod L.
1008             #pod * C – the maximum amount of time in milliseconds to allow the
1009             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
1010             #pod * C - a hash reference defining fields to return. See "L
1011             #pod fields to
1012             #pod return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>"
1013             #pod in the MongoDB documentation for details.
1014             #pod * C – either the string C<'before'> or C<'after'>, to indicate
1015             #pod whether the returned document should be the one before or after replacement.
1016             #pod The default is C<'before'>.
1017             #pod * C - the session to use for these operations. If not supplied, will
1018             #pod use an implicit session. For more information see L
1019             #pod * C – an L defining the order in
1020             #pod which to return matching documents. See docs for
1021             #pod L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
1022             #pod * C – defaults to false; if true, a new document will be added if one
1023             #pod is not found
1024             #pod
1025             #pod =cut
1026              
1027             my $foau_args;
1028             sub find_one_and_update {
1029 0 0 0 0 1   MongoDB::UsageError->throw("filter and update arguments must be references")
1030             unless ref( $_[1] ) && ref( $_[2] );
1031              
1032 0           my ( $self, $filter, $update, $options ) = @_;
1033 0           $options->{is_replace} = 0;
1034 0           return $self->_find_one_and_update_or_replace($filter, $update, $options);
1035             }
1036              
1037             #pod =method watch
1038             #pod
1039             #pod Watches for changes on this collection-
1040             #pod
1041             #pod Perform an aggregation with an implicit initial C<$changeStream> stage
1042             #pod and returns a L result which can be used to
1043             #pod iterate over the changes in the collection. This functionality is
1044             #pod available since MongoDB 3.6.
1045             #pod
1046             #pod my $stream = $collection->watch();
1047             #pod my $stream = $collection->watch( \@pipeline );
1048             #pod my $stream = $collection->watch( \@pipeline, \%options );
1049             #pod
1050             #pod while (1) {
1051             #pod
1052             #pod # This inner loop will only run until no more changes are
1053             #pod # available.
1054             #pod while (my $change = $stream->next) {
1055             #pod # process $change
1056             #pod }
1057             #pod }
1058             #pod
1059             #pod The returned stream will not block forever waiting for changes. If you
1060             #pod want to respond to changes over a longer time use C and
1061             #pod regularly call C in a loop.
1062             #pod
1063             #pod B: Using this helper method is preferred to manually aggregating
1064             #pod with a C<$changeStream> stage, since it will automatically resume when
1065             #pod the connection was terminated.
1066             #pod
1067             #pod The optional first argument must be an array-ref of
1068             #pod L
1069             #pod documents. Each pipeline document must be a hash reference. Not all
1070             #pod pipeline stages are supported after C<$changeStream>.
1071             #pod
1072             #pod The optional second argument is a hash reference with options:
1073             #pod
1074             #pod =for :list
1075             #pod * C - The fullDocument to pass as an option to the
1076             #pod C<$changeStream> stage. Allowed values: C, C.
1077             #pod Defaults to C. When set to C, the change
1078             #pod notification for partial updates will include both a delta describing the
1079             #pod changes to the document, as well as a copy of the entire document that
1080             #pod was changed from some time after the change occurred.
1081             #pod * C - The logical starting point for this change stream.
1082             #pod This value can be obtained from the C<_id> field of a document returned
1083             #pod by L. Cannot be specified together with
1084             #pod C
1085             #pod * C - The maximum number of milliseconds for the server
1086             #pod to wait before responding.
1087             #pod * C - A L specifying at what point
1088             #pod in time changes will start being watched. Cannot be specified together
1089             #pod with C. Plain values will be coerced to L
1090             #pod objects.
1091             #pod * C - the session to use for these operations. If not supplied, will
1092             #pod use an implicit session. For more information see L
1093             #pod
1094             #pod See L for more available options.
1095             #pod
1096             #pod See the L
1097             #pod for general usage information on change streams.
1098             #pod
1099             #pod See the L
1100             #pod for details on change streams.
1101             #pod
1102             #pod =cut
1103              
1104             sub watch {
1105 0     0 1   my ( $self, $pipeline, $options ) = @_;
1106              
1107 0   0       $pipeline ||= [];
1108 0   0       $options ||= {};
1109              
1110 0           my $session = $self->client->_get_session_from_hashref( $options );
1111              
1112             return MongoDB::ChangeStream->new(
1113             exists($options->{startAtOperationTime})
1114             ? (start_at_operation_time => delete $options->{startAtOperationTime})
1115             : (),
1116             exists($options->{fullDocument})
1117             ? (full_document => delete $options->{fullDocument})
1118             : (full_document => 'default'),
1119             exists($options->{resumeAfter})
1120             ? (resume_after => delete $options->{resumeAfter})
1121             : (),
1122             exists($options->{startAfter})
1123             ? (start_after => delete $options->{startAfter})
1124             : (),
1125             exists($options->{maxAwaitTimeMS})
1126             ? (max_await_time_ms => delete $options->{maxAwaitTimeMS})
1127 0 0         : (),
    0          
    0          
    0          
    0          
1128             client => $self->client,
1129             pipeline => $pipeline,
1130             session => $session,
1131             options => $options,
1132             op_args => $self->_op_args,
1133             );
1134             }
1135              
1136             #pod =method aggregate
1137             #pod
1138             #pod @pipeline = (
1139             #pod { '$group' => { _id => '$state,' totalPop => { '$sum' => '$pop' } } },
1140             #pod { '$match' => { totalPop => { '$gte' => 10 * 1000 * 1000 } } }
1141             #pod );
1142             #pod
1143             #pod $result = $collection->aggregate( \@pipeline );
1144             #pod $result = $collection->aggregate( \@pipeline, $options );
1145             #pod
1146             #pod Runs a query using the MongoDB 2.2+ aggregation framework and returns a
1147             #pod L object.
1148             #pod
1149             #pod The first argument must be an array-ref of L
1150             #pod pipeline|http://docs.mongodb.org/manual/core/aggregation-pipeline/> documents.
1151             #pod Each pipeline document must be a hash reference.
1152             #pod
1153             #pod B: Some pipeline documents have ordered arguments, such as C<$sort>.
1154             #pod Be sure to provide these argument using L. E.g.:
1155             #pod
1156             #pod { '$sort' => Tie::IxHash->new( age => -1, posts => 1 ) }
1157             #pod
1158             #pod A hash reference of options may be provided. Valid keys include:
1159             #pod
1160             #pod =for :list
1161             #pod * C – if, true enables writing to temporary files.
1162             #pod * C – the number of documents to return per batch.
1163             #pod * C - skips document validation, if enabled.
1164             #pod (Note, this will be ignored for servers before version 3.2.)
1165             #pod * C - a L defining the collation for this operation.
1166             #pod See docs for the format of the collation document here:
1167             #pod L.
1168             #pod * C – if true, return a single document with execution information.
1169             #pod * C – the maximum amount of time in milliseconds to allow the
1170             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
1171             #pod * C - An index to use for this aggregation. (Only compatible with servers
1172             #pod above version 3.6.) For more information, see the other aggregate options here:
1173             #pod L
1174             #pod * C - the session to use for these operations. If not supplied, will
1175             #pod use an implicit session. For more information see L
1176             #pod
1177             #pod B MongoDB 2.6+ added the '$out' pipeline operator. If this operator is
1178             #pod used to write aggregation results directly to a collection, an empty result
1179             #pod will be returned. Create a new collection> object to query the generated result
1180             #pod collection. When C<$out> is used, the command is treated as a write operation
1181             #pod and read preference is ignored.
1182             #pod
1183             #pod See L in the MongoDB manual
1184             #pod for more information on how to construct aggregation queries.
1185             #pod
1186             #pod B The use of aggregation cursors is automatic based on your server
1187             #pod version. However, if migrating a sharded cluster from MongoDB 2.4 to 2.6
1188             #pod or later, you must upgrade your mongod servers first before your mongos
1189             #pod routers or aggregation queries will fail. As a workaround, you may
1190             #pod pass C<< cursor => undef >> as an option.
1191             #pod
1192             #pod =cut
1193              
1194             my $aggregate_args;
1195             sub aggregate {
1196 0 0   0 1   MongoDB::UsageError->throw("pipeline argument must be an array reference")
1197             unless ref( $_[1] ) eq 'ARRAY';
1198              
1199 0           my ( $self, $pipeline, $options ) = @_;
1200 0   0       $options ||= {};
1201              
1202 0           my $session = $self->client->_get_session_from_hashref( $options );
1203              
1204             # boolify some options
1205 0           for my $k (qw/allowDiskUse explain/) {
1206 0 0         $options->{$k} = ( $options->{$k} ? true : false ) if exists $options->{$k};
    0          
1207             }
1208              
1209             # possibly fallback to default maxTimeMS
1210 0 0 0       if ( ! exists $options->{maxTimeMS} && $self->max_time_ms ) {
1211 0           $options->{maxTimeMS} = $self->max_time_ms;
1212             }
1213              
1214             # string is OK so we check ref, not just exists
1215 0 0         __ixhash( $options, 'hint' ) if ref $options->{hint};
1216              
1217             # read preferences are ignored if the last stage is $out
1218 0           my $last_op = '';
1219             # If $pipeline is an empty array, this can explode
1220 0 0         if ( scalar( @$pipeline ) > 0 ) { ($last_op) = keys %{ $pipeline->[-1] } };
  0            
  0            
1221 0           my $has_out = !!($last_op =~ m/\$out|\$merge/);
1222              
1223             my $op = MongoDB::Op::_Aggregate->_new(
1224             pipeline => $pipeline,
1225             options => $options,
1226             read_concern => $self->read_concern,
1227             has_out => $has_out,
1228             exists($options->{maxAwaitTimeMS})
1229             ? (maxAwaitTimeMS => delete $options->{maxAwaitTimeMS})
1230             : (),
1231             session => $session,
1232 0 0         %{ $self->_op_args },
  0            
1233             );
1234              
1235 0 0         return $has_out ?
1236             $self->client->send_read_op($op)
1237             : $self->client->send_retryable_read_op($op);
1238             }
1239              
1240             #pod =method count_documents
1241             #pod
1242             #pod $count = $coll->count_documents( $filter );
1243             #pod $count = $coll->count_documents( $filter, $options );
1244             #pod
1245             #pod Returns a count of documents matching a L.
1246             #pod To return a count of all documents, use an empty hash reference as the filter.
1247             #pod
1248             #pod B: this may result in a scan of all documents in the collection.
1249             #pod For a fast count of the total documents in a collection see
1250             #pod L instead.
1251             #pod
1252             #pod A hash reference of options may be provided. Valid keys include:
1253             #pod
1254             #pod =for :list
1255             #pod * C - a L defining the collation for this operation.
1256             #pod See docs for the format of the collation document here:
1257             #pod L.
1258             #pod * C – specify an index to use; must be a string, array reference,
1259             #pod hash reference or L object. (Requires server version 3.6 or later.)
1260             #pod * C – the maximum number of documents to count.
1261             #pod * C – the maximum amount of time in milliseconds to allow the
1262             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
1263             #pod * C – the number of documents to skip before counting documents.
1264             #pod * C - the session to use for these operations. If not supplied, will
1265             #pod use an implicit session. For more information see L
1266             #pod
1267             #pod B: When upgrading from the deprecated C method, some legacy
1268             #pod operators are not supported and must be replaced:
1269             #pod
1270             #pod +-------------+--------------------------------+
1271             #pod | Legacy | Modern Replacement |
1272             #pod +=============+================================+
1273             #pod | $where | $expr (Requires MongoDB 3.6+) |
1274             #pod +-------------+--------------------------------+
1275             #pod | $near | $geoWithin with $center |
1276             #pod +-------------+--------------------------------+
1277             #pod | $nearSphere | $geoWithin with $centerSphere |
1278             #pod +-------------+--------------------------------+
1279             #pod
1280             #pod =cut
1281              
1282             sub count_documents {
1283 0     0 1   my ( $self, $filter, $options ) = @_;
1284 0 0         MongoDB::UsageError->throw("filter argument must be a reference")
1285             unless ref( $filter );
1286              
1287 0   0       $options ||= {};
1288              
1289 0           my $pipeline = [ { '$match' => $filter } ];
1290              
1291 0 0         if ( exists $options->{skip} ) {
1292 0           push @$pipeline, { '$skip', delete $options->{skip} };
1293             }
1294              
1295 0 0         if ( exists $options->{limit} ) {
1296 0           push @$pipeline, { '$limit', delete $options->{limit} };
1297             }
1298              
1299 0           push @$pipeline, { '$group' => { '_id' => 1, 'n' => { '$sum' => 1 } } };
1300              
1301             # possibly fallback to default maxTimeMS
1302 0 0 0       if ( ! exists $options->{maxTimeMS} && $self->max_time_ms ) {
1303 0           $options->{maxTimeMS} = $self->max_time_ms;
1304             }
1305              
1306             # string is OK so we check ref, not just exists
1307 0 0         __ixhash($options, 'hint') if ref $options->{hint};
1308              
1309 0           my $res = $self->aggregate($pipeline, $options)->next;
1310              
1311 0   0       return $res->{n} // 0;
1312             }
1313              
1314             #pod =method estimated_document_count
1315             #pod
1316             #pod $count = $coll->estimated_document_count();
1317             #pod $count = $coll->estimated_document_count($options);
1318             #pod
1319             #pod Returns an estimated count of documents based on collection metadata.
1320             #pod
1321             #pod B: this method does not support sessions or transactions.
1322             #pod
1323             #pod A hash reference of options may be provided. Valid keys include:
1324             #pod
1325             #pod =for :list
1326             #pod * C – the maximum amount of time in milliseconds to allow the
1327             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
1328             #pod
1329             #pod =cut
1330              
1331             sub estimated_document_count {
1332 0     0 1   my ( $self, $options ) = @_;
1333 0   0       $options ||= {};
1334              
1335             # only maxTimeMS is supported
1336             my $filtered = {
1337 0 0         ( exists $options->{maxTimeMS} ? ( maxTimeMS => $options->{maxTimeMS} ) : () )
1338             };
1339              
1340             # possibly fallback to default maxTimeMS
1341 0 0 0       if ( ! exists $filtered->{maxTimeMS} && $self->max_time_ms ) {
1342 0           $filtered->{maxTimeMS} = $self->max_time_ms;
1343             }
1344              
1345             # XXX replace this with direct use of a command op?
1346             my $op = MongoDB::Op::_Count->_new(
1347             options => $filtered,
1348             filter => undef,
1349             session => $self->client->_maybe_get_implicit_session,
1350 0           %{ $self->_op_args },
  0            
1351             );
1352              
1353 0           my $res = $self->client->send_retryable_read_op($op);
1354              
1355 0   0       return $res->{n} // 0;
1356             }
1357              
1358             #pod =method distinct
1359             #pod
1360             #pod $result = $coll->distinct( $fieldname );
1361             #pod $result = $coll->distinct( $fieldname, $filter );
1362             #pod $result = $coll->distinct( $fieldname, $filter, $options );
1363             #pod
1364             #pod Returns a L object that will provide distinct values for
1365             #pod a specified field name.
1366             #pod
1367             #pod The query may be limited by an optional L
1368             #pod expression>.
1369             #pod
1370             #pod A hash reference of options may be provided. Valid keys include:
1371             #pod
1372             #pod =for :list
1373             #pod * C - a L defining the collation for this operation.
1374             #pod See docs for the format of the collation document here:
1375             #pod L.
1376             #pod * C – the maximum amount of time in milliseconds to allow the
1377             #pod command to run. (Note, this will be ignored for servers before version 2.6.)
1378             #pod * C - the session to use for these operations. If not supplied, will
1379             #pod use an implicit session. For more information see L
1380             #pod
1381             #pod See documentation for the L
1382             #pod command|http://docs.mongodb.org/manual/reference/command/distinct/> for
1383             #pod details.
1384             #pod
1385             #pod =cut
1386              
1387             my $distinct_args;
1388              
1389             sub distinct {
1390 0 0   0 1   MongoDB::UsageError->throw("fieldname argument is required")
1391             unless defined( $_[1] );
1392              
1393 0           my ( $self, $fieldname, $filter, $options ) = @_;
1394 0   0       $filter ||= {};
1395 0   0       $options ||= {};
1396              
1397             # possibly fallback to default maxTimeMS
1398 0 0 0       if ( ! exists $options->{maxTimeMS} && $self->max_time_ms ) {
1399 0           $options->{maxTimeMS} = $self->max_time_ms;
1400             }
1401              
1402 0           my $session = $self->client->_get_session_from_hashref( $options );
1403              
1404             my $op = MongoDB::Op::_Distinct->_new(
1405             fieldname => $fieldname,
1406             filter => $filter,
1407             options => $options,
1408             session => $session,
1409 0           %{ $self->_op_args },
  0            
1410             );
1411              
1412 0           return $self->client->send_retryable_read_op($op);
1413             }
1414              
1415             #pod =method rename
1416             #pod
1417             #pod $newcollection = $collection->rename("mynewcollection");
1418             #pod
1419             #pod Renames the collection. If a collection already exists with the new collection
1420             #pod name, this method will throw an exception.
1421             #pod
1422             #pod A hashref of options may be provided.
1423             #pod
1424             #pod Valid options include:
1425             #pod
1426             #pod =for :list
1427             #pod * C - the session to use for these operations. If not supplied, will
1428             #pod use an implicit session. For more information see L
1429             #pod
1430             #pod It returns a new L object corresponding to the renamed
1431             #pod collection.
1432             #pod
1433             #pod =cut
1434              
1435             sub rename {
1436 0     0 1   my ( $self, $new_name, $options ) = @_;
1437              
1438 0           my $session = $self->client->_get_session_from_hashref( $options );
1439              
1440             my $op = MongoDB::Op::_RenameCollection->_new(
1441             src_ns => $self->full_name,
1442             dst_ns => join( ".", $self->database->name, $new_name ),
1443             options => $options,
1444             session => $session,
1445 0           %{ $self->_op_args },
  0            
1446             );
1447              
1448 0           $self->client->send_write_op($op);
1449              
1450 0           return $self->database->get_collection($new_name);
1451             }
1452              
1453             #pod =method drop
1454             #pod
1455             #pod $collection->drop;
1456             #pod
1457             #pod Deletes a collection as well as all of its indexes.
1458             #pod
1459             #pod =cut
1460              
1461             sub drop {
1462 0     0 1   my ( $self, $options ) = @_;
1463              
1464 0           my $session = $self->client->_get_session_from_hashref( $options );
1465              
1466             $self->client->send_write_op(
1467             MongoDB::Op::_DropCollection->_new(
1468             options => $options,
1469             session => $session,
1470 0           %{ $self->_op_args },
  0            
1471             )
1472             );
1473              
1474 0           return;
1475             }
1476              
1477             #pod =method ordered_bulk
1478             #pod
1479             #pod $bulk = $coll->ordered_bulk;
1480             #pod $bulk->insert_one( $doc1 );
1481             #pod $bulk->insert_one( $doc2 );
1482             #pod ...
1483             #pod $result = $bulk->execute;
1484             #pod
1485             #pod Returns a L object to group write operations into fewer network
1486             #pod round-trips. This method creates an B operation, where operations halt after
1487             #pod the first error. See L for more details.
1488             #pod
1489             #pod The method C may be used as an alias.
1490             #pod
1491             #pod A hash reference of options may be provided.
1492             #pod
1493             #pod Valid options include:
1494             #pod
1495             #pod =for :list
1496             #pod * C - skips document validation, if enabled; this
1497             #pod is ignored for MongoDB servers older than version 3.2.
1498             #pod
1499             #pod =cut
1500              
1501             sub initialize_ordered_bulk_op {
1502 0     0 0   my ($self, $args) = @_;
1503 0   0       $args ||= {};
1504 0           return MongoDB::BulkWrite->new( %$args, collection => $self, ordered => 1, );
1505             }
1506              
1507             #pod =method unordered_bulk
1508             #pod
1509             #pod This method works just like L except that the order that
1510             #pod operations are sent to the database is not guaranteed and errors do not halt processing.
1511             #pod See L for more details.
1512             #pod
1513             #pod The method C may be used as an alias.
1514             #pod
1515             #pod A hash reference of options may be provided.
1516             #pod
1517             #pod Valid options include:
1518             #pod
1519             #pod =for :list
1520             #pod * C - skips document validation, if enabled; this
1521             #pod is ignored for MongoDB servers older than version 3.2.
1522             #pod
1523             #pod =cut
1524              
1525             sub initialize_unordered_bulk_op {
1526 0     0 0   my ($self, $args) = @_;
1527 0   0       $args ||= {};
1528 0           return MongoDB::BulkWrite->new( %$args, collection => $self, ordered => 0 );
1529             }
1530              
1531             #pod =method bulk_write
1532             #pod
1533             #pod $res = $coll->bulk_write( [ @requests ], $options )
1534             #pod
1535             #pod This method provides syntactic sugar to construct and execute a bulk operation
1536             #pod directly, without using C or
1537             #pod C to generate a L object and
1538             #pod then calling methods on it. It returns a L object
1539             #pod just like the L method.
1540             #pod
1541             #pod The first argument must be an array reference of requests. Requests consist
1542             #pod of pairs of a MongoDB::Collection write method name (e.g. C,
1543             #pod C) and an array reference of arguments to the corresponding
1544             #pod method name. They may be given as pairs, or as hash or array
1545             #pod references:
1546             #pod
1547             #pod # pairs -- most efficient
1548             #pod @requests = (
1549             #pod insert_one => [ { x => 1 } ],
1550             #pod replace_one => [ { x => 1 }, { x => 4 } ],
1551             #pod delete_one => [ { x => 4 } ],
1552             #pod update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ],
1553             #pod );
1554             #pod
1555             #pod # hash references
1556             #pod @requests = (
1557             #pod { insert_one => [ { x => 1 } ] },
1558             #pod { replace_one => [ { x => 1 }, { x => 4 } ] },
1559             #pod { delete_one => [ { x => 4 } ] },
1560             #pod { update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] },
1561             #pod );
1562             #pod
1563             #pod # array references
1564             #pod @requests = (
1565             #pod [ insert_one => [ { x => 1 } ] ],
1566             #pod [ replace_one => [ { x => 1 }, { x => 4 } ] ],
1567             #pod [ delete_one => [ { x => 4 } ] ],
1568             #pod [ update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] ],
1569             #pod );
1570             #pod
1571             #pod Valid method names include C, C, C,
1572             #pod C C, C, C.
1573             #pod
1574             #pod An optional hash reference of options may be provided.
1575             #pod
1576             #pod Valid options include:
1577             #pod
1578             #pod =for :list
1579             #pod * C - skips document validation, if enabled; this
1580             #pod is ignored for MongoDB servers older than version 3.2.
1581             #pod * C – when true, the bulk operation is executed like
1582             #pod L. When false, the bulk operation is executed
1583             #pod like L. The default is true.
1584             #pod * C - the session to use for these operations. If not supplied, will
1585             #pod use an implicit session. For more information see L
1586             #pod
1587             #pod See L for more details on bulk writes. Be advised that
1588             #pod the legacy Bulk API method names differ slightly from MongoDB::Collection
1589             #pod method names.
1590             #pod
1591             #pod =cut
1592              
1593             sub bulk_write {
1594 0     0 1   my ( $self, $requests, $options ) = @_;
1595              
1596 0 0         MongoDB::UsageError->throw("requests not an array reference")
1597             unless ref $requests eq 'ARRAY';
1598 0 0         MongoDB::UsageError->throw("empty request list") unless @$requests;
1599 0 0 0       MongoDB::UsageError->throw("options not a hash reference")
1600             if defined($options) && ref($options) ne 'HASH';
1601              
1602 0   0       $options ||= {};
1603              
1604 0 0         my $ordered = exists $options->{ordered} ? delete $options->{ordered} : 1;
1605              
1606 0           my $session = $self->client->_get_session_from_hashref( $options );
1607              
1608 0 0         my $bulk =
1609             $ordered ? $self->ordered_bulk($options) : $self->unordered_bulk($options);
1610              
1611 0           my $i = 0;
1612              
1613 0           while ( $i <= $#$requests ) {
1614 0           my ( $method, $args );
1615              
1616             # pull off document or pair
1617 0 0         if ( my $type = ref $requests->[$i] ) {
1618 0 0         if ( $type eq 'ARRAY' ) {
    0          
1619 0           ( $method, $args ) = @{ $requests->[$i] };
  0            
1620             }
1621             elsif ( $type eq 'HASH' ) {
1622 0           ( $method, $args ) = %{ $requests->[$i] };
  0            
1623             }
1624             else {
1625 0           MongoDB::UsageError->throw("$requests->[$i] is not a hash or array reference");
1626             }
1627 0           $i++;
1628             }
1629             else {
1630 0           ( $method, $args ) = @{$requests}[ $i, $i + 1 ];
  0            
1631 0           $i += 2;
1632             }
1633              
1634 0 0         MongoDB::UsageError->throw("'$method' requires an array reference of arguments")
1635             unless ref($args) eq 'ARRAY';
1636              
1637             # handle inserts
1638 0 0 0       if ( $method eq 'insert_one' || $method eq 'insert_many' ) {
1639 0           $bulk->insert_one($_) for @$args;
1640             }
1641             else {
1642 0           my ( $filter, $arg2, $arg3 ) = @$args;
1643              
1644 0   0       my $is_delete = $method eq 'delete_one' || $method eq 'delete_many';
1645 0 0         my $update_doc = $is_delete ? undef : $arg2;
1646 0 0         my $opts = $is_delete ? $arg2 : $arg3;
1647              
1648 0           my $view = $bulk->find($filter);
1649              
1650             # set collation
1651 0 0 0       $view = $view->collation( $opts->{collation} ) if $opts && $opts->{collation};
1652              
1653             # handle deletes
1654 0 0         if ( $method eq 'delete_one' ) {
    0          
1655 0           $view->delete_one;
1656 0           next;
1657             }
1658             elsif ( $method eq 'delete_many' ) {
1659 0           $view->delete_many;
1660 0           $bulk->_retryable( 0 );
1661 0           next;
1662             }
1663              
1664             # updates might be upserts
1665 0 0 0       $view = $view->upsert if $opts && $opts->{upsert};
1666              
1667             # handle updates
1668 0 0         if ( $method eq 'replace_one' ) {
    0          
    0          
1669 0           $view->replace_one($update_doc);
1670             }
1671             elsif ( $method eq 'update_one' ) {
1672 0           $view->update_one($update_doc);
1673             }
1674             elsif ( $method eq 'update_many' ) {
1675 0           $view->update_many($update_doc);
1676 0           $bulk->_retryable( 0 );
1677             }
1678             else {
1679 0           MongoDB::UsageError->throw("unknown bulk operation '$method'");
1680             }
1681             }
1682             }
1683              
1684             return $bulk->execute(
1685             $options->{writeConcern},
1686 0           { session => $session },
1687             );
1688             }
1689              
1690             BEGIN {
1691             # aliases
1692 59     59   257657 no warnings 'once';
  59         163  
  59         4141  
1693 59     59   291 *query = \&find;
1694 59         177 *ordered_bulk = \&initialize_ordered_bulk_op;
1695 59         61610 *unordered_bulk = \&initialize_unordered_bulk_op;
1696             }
1697              
1698             #--------------------------------------------------------------------------#
1699             # private methods
1700             #--------------------------------------------------------------------------#
1701              
1702             sub _dynamic_write_concern {
1703 0     0     my ( $self, $opts ) = @_;
1704 0 0 0       if ( !exists( $opts->{safe} ) || $opts->{safe} ) {
1705 0           return $self->write_concern;
1706             }
1707             else {
1708 0           return MongoDB::WriteConcern->new( w => 0 );
1709             }
1710             }
1711              
1712             sub _find_one_and_update_or_replace {
1713 0     0     my ($self, $filter, $modifier, $options) = @_;
1714 0   0       $options ||= {};
1715 0           my $is_replace = delete $options->{is_replace};
1716              
1717             # rename projection -> fields
1718 0 0         $options->{fields} = delete $options->{projection} if exists $options->{projection};
1719              
1720             # possibly fallback to default maxTimeMS
1721 0 0 0       if ( ! exists $options->{maxTimeMS} && $self->max_time_ms ) {
1722 0           $options->{maxTimeMS} = $self->max_time_ms;
1723             }
1724              
1725             # coerce to IxHash
1726 0           __ixhash($options, 'sort');
1727              
1728             # returnDocument ('before'|'after') maps to field 'new'
1729 0 0         if ( exists $options->{returnDocument} ) {
1730             MongoDB::UsageError->throw("Invalid returnDocument parameter '$options->{returnDocument}'")
1731 0 0         unless $options->{returnDocument} =~ /^(?:before|after)$/;
1732 0 0         $options->{new} = delete( $options->{returnDocument} ) eq 'after' ? true : false;
1733             }
1734              
1735             # pass separately for MongoDB::Role::_BypassValidation
1736 0           my $bypass = delete $options->{bypassDocumentValidation};
1737              
1738 0           my $session = $self->client->_get_session_from_hashref( $options );
1739              
1740             my $op = MongoDB::Op::_FindAndUpdate->_new(
1741             filter => $filter,
1742             modifier => $modifier,
1743             options => $options,
1744             bypassDocumentValidation => $bypass,
1745             session => $session,
1746             is_replace => $is_replace,
1747 0           %{ $self->_op_args },
  0            
1748             );
1749              
1750 0 0         return $op->_should_use_acknowledged_write
1751             ? $self->client->send_retryable_write_op( $op )
1752             : $self->client->send_write_op( $op );
1753             }
1754              
1755             #--------------------------------------------------------------------------#
1756             # Deprecated functions
1757             #--------------------------------------------------------------------------#
1758              
1759             sub parallel_scan {
1760 0     0 0   my ( $self, $num_cursors, $options ) = @_;
1761 0           $self->_warn_deprecated_method('parallel_scan' => []);
1762              
1763 0 0 0       unless (defined $num_cursors && $num_cursors == int($num_cursors)
      0        
      0        
1764             && $num_cursors > 0 && $num_cursors <= 10000
1765             ) {
1766 0           MongoDB::UsageError->throw( "first argument to parallel_scan must be a positive integer between 1 and 10000" )
1767             }
1768 0 0         $options = ref $options eq 'HASH' ? $options : { };
1769              
1770             my $op = MongoDB::Op::_ParallelScan->_new(
1771 0           %{ $self->_op_args },
  0            
1772             num_cursors => $num_cursors,
1773             options => $options,
1774             );
1775              
1776 0           my $result = $self->client->send_read_op( $op );
1777 0           my $response = $result->output;
1778              
1779             MongoDB::UsageError->throw("No cursors returned")
1780 0 0 0       unless $response->{cursors} && ref $response->{cursors} eq 'ARRAY';
1781              
1782 0           my @cursors;
1783 0           for my $c ( map { $_->{cursor} } @{$response->{cursors}} ) {
  0            
  0            
1784 0           my $batch = $c->{firstBatch};
1785             my $qr = MongoDB::QueryResult->_new(
1786             _client => $self->client,
1787             _address => $result->address,
1788             _full_name => $c->{ns},
1789             _bson_codec => $self->bson_codec,
1790             _batch_size => scalar @$batch,
1791             _cursor_at => 0,
1792             _limit => 0,
1793             _cursor_id => $c->{id},
1794 0           _cursor_start => 0,
1795             _cursor_flags => {},
1796             _cursor_num => scalar @$batch,
1797             _docs => $batch,
1798             );
1799 0           push @cursors, $qr;
1800             }
1801              
1802 0           return @cursors;
1803             }
1804              
1805             sub count {
1806 0     0 0   my ( $self, $filter, $options ) = @_;
1807              
1808 0           $self->_warn_deprecated_method( 'count' => [qw/count_documents estimated_document_count/] );
1809              
1810 0   0       $filter ||= {};
1811 0   0       $options ||= {};
1812              
1813             # possibly fallback to default maxTimeMS
1814 0 0 0       if ( !exists $options->{maxTimeMS} && $self->max_time_ms ) {
1815 0           $options->{maxTimeMS} = $self->max_time_ms;
1816             }
1817              
1818 0           my $session = $self->client->_get_session_from_hashref($options);
1819              
1820             # string is OK so we check ref, not just exists
1821 0 0         __ixhash( $options, 'hint' ) if ref $options->{hint};
1822              
1823             my $op = MongoDB::Op::_Count->_new(
1824             options => $options,
1825             filter => $filter,
1826             session => $session,
1827 0           %{ $self->_op_args },
  0            
1828             );
1829              
1830 0           my $res = $self->client->send_read_op($op);
1831              
1832 0           return $res->{n};
1833             }
1834              
1835             #--------------------------------------------------------------------------#
1836             # utility function
1837             #--------------------------------------------------------------------------#
1838              
1839             # utility function to coerce array/hashref to Tie::Ixhash
1840             sub __ixhash {
1841 0     0     my ($hash, $key) = @_;
1842 0 0         return unless exists $hash->{$key};
1843 0           my $ref = $hash->{$key};
1844 0           my $type = ref($ref);
1845 0 0         return if $type eq 'Tie::IxHash';
1846 0 0 0       if ( $type eq 'HASH' ) {
    0          
1847 0           $hash->{$key} = Tie::IxHash->new( %$ref );
1848             }
1849             elsif ( $type eq 'ARRAY' || $type eq 'BSON::Doc' ) {
1850 0           $hash->{$key} = Tie::IxHash->new( @$ref );
1851             }
1852             else {
1853 0           MongoDB::UsageError->throw("Can't convert $type to a Tie::IxHash");
1854             }
1855 0           return;
1856             }
1857              
1858             # we have a private _run_command rather than using the 'database' attribute
1859             # so that we're using our BSON codec and not the source database one
1860             sub _run_command {
1861 0     0     my ( $self, $command ) = @_;
1862              
1863 0           my $op = MongoDB::Op::_Command->_new(
1864             db_name => $self->database->name,
1865             query => $command,
1866             query_flags => {},
1867             bson_codec => $self->bson_codec,
1868             monitoring_callback => $self->client->monitoring_callback,
1869             );
1870              
1871 0           my $obj = $self->client->send_retryable_read_op($op);
1872              
1873 0           return $obj->output;
1874             }
1875              
1876             1;
1877              
1878             =pod
1879              
1880             =encoding UTF-8
1881              
1882             =head1 NAME
1883              
1884             MongoDB::Collection - A MongoDB Collection
1885              
1886             =head1 VERSION
1887              
1888             version v2.2.2
1889              
1890             =head1 SYNOPSIS
1891              
1892             # get a Collection via the Database object
1893             $coll = $db->get_collection("people");
1894              
1895             # insert a document
1896             $coll->insert_one( { name => "John Doe", age => 42 } );
1897              
1898             # insert one or more documents
1899             $coll->insert_many( \@documents );
1900              
1901             # delete a document
1902             $coll->delete_one( { name => "John Doe" } );
1903              
1904             # update a document
1905             $coll->update_one( { name => "John Doe" }, { '$inc' => { age => 1 } } );
1906              
1907             # find a single document
1908             $doc = $coll->find_one( { name => "John Doe" } )
1909              
1910             # Get a MongoDB::Cursor for a query
1911             $cursor = $coll->find( { age => 42 } );
1912              
1913             # Cursor iteration
1914             while ( my $doc = $cursor->next ) {
1915             ...
1916             }
1917              
1918             =head1 DESCRIPTION
1919              
1920             This class models a MongoDB collection and provides an API for interacting
1921             with it.
1922              
1923             Generally, you never construct one of these directly with C. Instead, you
1924             call C on a L object.
1925              
1926             =head1 USAGE
1927              
1928             =head2 Error handling
1929              
1930             Unless otherwise explicitly documented, all methods throw exceptions if
1931             an error occurs. The error types are documented in L.
1932              
1933             To catch and handle errors, the L and L modules
1934             are recommended:
1935              
1936             use Try::Tiny;
1937             use Safe::Isa; # provides $_isa
1938              
1939             try {
1940             $coll->insert_one( $doc )
1941             }
1942             catch {
1943             if ( $_->$_isa("MongoDB::DuplicateKeyError" ) {
1944             ...
1945             }
1946             else {
1947             ...
1948             }
1949             };
1950              
1951             To retry failures automatically, consider using L.
1952              
1953             =head2 Transactions
1954              
1955             To conduct operations in a transactions, get a L
1956             from L. Start the transaction on the
1957             session using C and pass the session as an option to all
1958             operations. Then call C or C on the
1959             session. See the L for options and usage details.
1960              
1961             For detailed instructions on using transactions with MongoDB, see the
1962             MongoDB manual page:
1963             L.
1964              
1965             =head2 Terminology
1966              
1967             =head3 Document
1968              
1969             A collection of key-value pairs. A Perl hash is a document. Array
1970             references with an even number of elements and L objects may also
1971             be used as documents.
1972              
1973             =head3 Ordered document
1974              
1975             Many MongoDB::Collection method parameters or options require an B
1976             document>: an ordered list of key/value pairs. Perl's hashes are B
1977             ordered and since Perl v5.18 are guaranteed to have random order. Therefore,
1978             when an ordered document is called for, you may use an array reference of pairs
1979             or a L object. You may use a hash reference if there is only
1980             one key/value pair.
1981              
1982             =head3 Filter expression
1983              
1984             A filter expression provides the L
1985             criteria|http://docs.mongodb.org/manual/tutorial/query-documents/> to select a
1986             document for deletion. It must be an L.
1987              
1988             =head1 ATTRIBUTES
1989              
1990             =head2 database
1991              
1992             The L representing the database that contains
1993             the collection.
1994              
1995             =head2 name
1996              
1997             The name of the collection.
1998              
1999             =head2 read_preference
2000              
2001             A L object. It may be initialized with a string
2002             corresponding to one of the valid read preference modes or a hash reference
2003             that will be coerced into a new MongoDB::ReadPreference object.
2004             By default it will be inherited from a L object.
2005              
2006             =head2 write_concern
2007              
2008             A L object. It may be initialized with a hash
2009             reference that will be coerced into a new MongoDB::WriteConcern object.
2010             By default it will be inherited from a L object.
2011              
2012             =head2 read_concern
2013              
2014             A L object. May be initialized with a hash
2015             reference or a string that will be coerced into the level of read
2016             concern.
2017              
2018             By default it will be inherited from a L object.
2019              
2020             =head2 max_time_ms
2021              
2022             Specifies the default maximum amount of time in milliseconds that the
2023             server should use for working on a query.
2024              
2025             B: this will only be used for server versions 2.6 or greater, as that
2026             was when the C<$maxTimeMS> meta-operator was introduced.
2027              
2028             =head2 bson_codec
2029              
2030             An object that provides the C and C methods, such
2031             as from L. It may be initialized with a hash reference that
2032             will be coerced into a new L object. By default it will be
2033             inherited from a L object.
2034              
2035             =head1 METHODS
2036              
2037             =head2 client
2038              
2039             $client = $coll->client;
2040              
2041             Returns the L object associated with this
2042             object.
2043              
2044             =head2 full_name
2045              
2046             $full_name = $coll->full_name;
2047              
2048             Returns the full name of the collection, including the namespace of the
2049             database it's in prefixed with a dot character. E.g. collection "foo" in
2050             database "test" would result in a C of "test.foo".
2051              
2052             =head2 indexes
2053              
2054             $indexes = $collection->indexes;
2055              
2056             $collection->indexes->create_one( [ x => 1 ], { unique => 1 } );
2057             $collection->indexes->drop_all;
2058              
2059             Returns a L object for managing the indexes associated
2060             with the collection.
2061              
2062             =head2 clone
2063              
2064             $coll2 = $coll1->clone( write_concern => { w => 2 } );
2065              
2066             Constructs a copy of the original collection, but allows changing
2067             attributes in the copy.
2068              
2069             =head2 with_codec
2070              
2071             $coll2 = $coll1->with_codec( $new_codec );
2072             $coll2 = $coll1->with_codec( prefer_numeric => 1 );
2073              
2074             Constructs a copy of the original collection, but clones the C.
2075             If given an object that does C and C, it is
2076             equivalent to:
2077              
2078             $coll2 = $coll1->clone( bson_codec => $new_codec );
2079              
2080             If given a hash reference or a list of key/value pairs, it is equivalent
2081             to:
2082              
2083             $coll2 = $coll1->clone(
2084             bson_codec => $coll1->bson_codec->clone( @list )
2085             );
2086              
2087             =head2 insert_one
2088              
2089             $res = $coll->insert_one( $document );
2090             $res = $coll->insert_one( $document, $options );
2091             $id = $res->inserted_id;
2092              
2093             Inserts a single L into the database and returns a
2094             L or L object.
2095              
2096             If no C<_id> field is present, one will be added when a document is
2097             serialized for the database without modifying the original document.
2098             The generated C<_id> may be retrieved from the result object.
2099              
2100             An optional hash reference of options may be given.
2101              
2102             Valid options include:
2103              
2104             =over 4
2105              
2106             =item *
2107              
2108             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2109              
2110             =item *
2111              
2112             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2113              
2114             =back
2115              
2116             =head2 insert_many
2117              
2118             $res = $coll->insert_many( [ @documents ] );
2119             $res = $coll->insert_many( [ @documents ], { ordered => 0 } );
2120              
2121             Inserts each of the L in an array reference into the
2122             database and returns a L or
2123             L. This is syntactic sugar for doing a
2124             L operation.
2125              
2126             If no C<_id> field is present, one will be added when a document is
2127             serialized for the database without modifying the original document.
2128             The generated C<_id> may be retrieved from the result object.
2129              
2130             An optional hash reference of options may be provided.
2131              
2132             Valid options include:
2133              
2134             =over 4
2135              
2136             =item *
2137              
2138             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2139              
2140             =item *
2141              
2142             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2143              
2144             =item *
2145              
2146             C – 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.
2147              
2148             =back
2149              
2150             On MongoDB servers before version 2.6, C bulk operations are
2151             emulated with individual inserts to capture error information. On 2.6 or
2152             later, this method will be significantly faster than individual C
2153             calls.
2154              
2155             =head2 delete_one
2156              
2157             $res = $coll->delete_one( $filter );
2158             $res = $coll->delete_one( { _id => $id } );
2159             $res = $coll->delete_one( $filter, { collation => { locale => "en_US" } } );
2160              
2161             Deletes a single document that matches a L and returns a
2162             L or L object.
2163              
2164             A hash reference of options may be provided.
2165              
2166             Valid options include:
2167              
2168             =over 4
2169              
2170             =item *
2171              
2172             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2173              
2174             =item *
2175              
2176             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2177              
2178             =back
2179              
2180             =head2 delete_many
2181              
2182             $res = $coll->delete_many( $filter );
2183             $res = $coll->delete_many( { name => "Larry" } );
2184             $res = $coll->delete_many( $filter, { collation => { locale => "en_US" } } );
2185              
2186             Deletes all documents that match a L
2187             and returns a L or L
2188             object.
2189              
2190             Valid options include:
2191              
2192             =over 4
2193              
2194             =item *
2195              
2196             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2197              
2198             =item *
2199              
2200             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2201              
2202             =back
2203              
2204             =head2 replace_one
2205              
2206             $res = $coll->replace_one( $filter, $replacement );
2207             $res = $coll->replace_one( $filter, $replacement, { upsert => 1 } );
2208              
2209             Replaces one document that matches a L
2210             expression> and returns a L or
2211             L object.
2212              
2213             The replacement document must not have any field-update operators in it (e.g.
2214             C<$set>).
2215              
2216             A hash reference of options may be provided.
2217              
2218             Valid options include:
2219              
2220             =over 4
2221              
2222             =item *
2223              
2224             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2225              
2226             =item *
2227              
2228             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2229              
2230             =item *
2231              
2232             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2233              
2234             =item *
2235              
2236             C – defaults to false; if true, a new document will be added if one is not found
2237              
2238             =back
2239              
2240             =head2 update_one
2241              
2242             $res = $coll->update_one( $filter, $update );
2243             $res = $coll->update_one( $filter, $update, { upsert => 1 } );
2244              
2245             Updates one document that matches a L
2246             and returns a L or L
2247             object.
2248              
2249             The update document must have only field-update operators in it (e.g.
2250             C<$set>).
2251              
2252             A hash reference of options may be provided.
2253              
2254             Valid options include:
2255              
2256             =over 4
2257              
2258             =item *
2259              
2260             C - 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+.
2261              
2262             =item *
2263              
2264             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2265              
2266             =item *
2267              
2268             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2269              
2270             =item *
2271              
2272             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2273              
2274             =item *
2275              
2276             C – 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.
2277              
2278             =back
2279              
2280             =head2 update_many
2281              
2282             $res = $coll->update_many( $filter, $update );
2283             $res = $coll->update_many( $filter, $update, { upsert => 1 } );
2284              
2285             Updates one or more documents that match a L
2286             expression> and returns a L or
2287             L object.
2288              
2289             The update document must have only field-update operators in it (e.g.
2290             C<$set>).
2291              
2292             A hash reference of options may be provided.
2293              
2294             Valid options include:
2295              
2296             =over 4
2297              
2298             =item *
2299              
2300             C - 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+.
2301              
2302             =item *
2303              
2304             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2305              
2306             =item *
2307              
2308             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2309              
2310             =item *
2311              
2312             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2313              
2314             =item *
2315              
2316             C – 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.
2317              
2318             =back
2319              
2320             =head2 find
2321              
2322             $cursor = $coll->find( $filter );
2323             $cursor = $coll->find( $filter, $options );
2324              
2325             $cursor = $coll->find({ i => { '$gt' => 42 } }, {limit => 20});
2326              
2327             Executes a query with a L and returns a
2328             B C object. (The query is not immediately
2329             issued to the server; see below for details.)
2330              
2331             The query can be customized using L methods, or with an
2332             optional hash reference of options.
2333              
2334             Valid options include:
2335              
2336             =over 4
2337              
2338             =item *
2339              
2340             C - get partial results from a mongos if some shards are down (instead of throwing an error).
2341              
2342             =item *
2343              
2344             C – the number of documents to return per batch.
2345              
2346             =item *
2347              
2348             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2349              
2350             =item *
2351              
2352             C – attaches a comment to the query.
2353              
2354             =item *
2355              
2356             C – indicates the type of cursor to use. It must be one of three string values: C<'non_tailable'> (the default), C<'tailable'>, and C<'tailable_await'>.
2357              
2358             =item *
2359              
2360             C – L; must be a string, array reference, hash reference or L object.
2361              
2362             =item *
2363              
2364             C – the maximum number of documents to return.
2365              
2366             =item *
2367              
2368             C – L upper bound for a specific index| https://docs.mongodb.com/manual/reference/operator/meta/max/>.
2369              
2370             =item *
2371              
2372             C – the maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. This only applies to a C of 'tailable_await'; the option is otherwise ignored. (Note, this will be ignored for servers before version 3.2.)
2373              
2374             =item *
2375              
2376             C – (DEPRECATED) L.
2377              
2378             =item *
2379              
2380             C – the maximum amount of time to allow the query to run. (Note, this will be ignored for servers before version 2.6.)
2381              
2382             =item *
2383              
2384             C – L lower bound for a specific index| https://docs.mongodb.com/manual/reference/operator/meta/min/>.
2385              
2386             =item *
2387              
2388             C – (DEPRECATED) a hash reference of dollar-prefixed L 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.
2389              
2390             =item *
2391              
2392             C – if true, prevents the server from timing out a cursor after a period of inactivity.
2393              
2394             =item *
2395              
2396             C - a hash reference defining fields to return. See "L" in the MongoDB documentation for details.
2397              
2398             =item *
2399              
2400             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2401              
2402             =item *
2403              
2404             C – L.
2405              
2406             =item *
2407              
2408             C – modifies the output of a query by adding a field L<$recordId|https://docs.mongodb.com/manual/reference/method/cursor.showRecordId/> that uniquely identifies a document in a collection.
2409              
2410             =item *
2411              
2412             C – the number of documents to skip before returning.
2413              
2414             =item *
2415              
2416             C – an L defining the order in which to return matching documents. See the L<$orderby documentation|https://docs.mongodb.com/manual/reference/operator/meta/orderby/> for examples.
2417              
2418             =back
2419              
2420             For more information, see the L
2421             Overview|http://docs.mongodb.org/manual/core/read-operations-introduction/> in
2422             the MongoDB documentation.
2423              
2424             B, a L object holds the query and does not issue the
2425             query to the server until the L method is
2426             called on it or until an iterator method like L
2427             is called. Performance will be better directly on a
2428             L object:
2429              
2430             my $query_result = $coll->find( $filter )->result;
2431              
2432             while ( my $next = $query_result->next ) {
2433             ...
2434             }
2435              
2436             =head2 find_one
2437              
2438             $doc = $collection->find_one( $filter, $projection );
2439             $doc = $collection->find_one( $filter, $projection, $options );
2440              
2441             Executes a query with a L and returns a
2442             single document.
2443              
2444             If a projection argument is provided, it must be a hash reference specifying
2445             fields to return. See L
2446             return|http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>
2447             in the MongoDB documentation for details.
2448              
2449             If only a filter is provided or if the projection document is an empty hash
2450             reference, all fields will be returned.
2451              
2452             my $doc = $collection->find_one( $filter );
2453             my $doc = $collection->find_one( $filter, {}, $options );
2454              
2455             A hash reference of options may be provided as a third argument. Valid keys
2456             include:
2457              
2458             =over 4
2459              
2460             =item *
2461              
2462             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2463              
2464             =item *
2465              
2466             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2467              
2468             =item *
2469              
2470             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2471              
2472             =item *
2473              
2474             C – an L defining the order in which to return matching documents. If C<$orderby> also exists in the modifiers document, the sort field overwrites C<$orderby>. See docs for L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
2475              
2476             =back
2477              
2478             See also core documentation on querying:
2479             L.
2480              
2481             =head2 find_id
2482              
2483             $doc = $collection->find_id( $id );
2484             $doc = $collection->find_id( $id, $projection );
2485             $doc = $collection->find_id( $id, $projection, $options );
2486              
2487             Executes a query with a L of C<< { _id
2488             => $id } >> and returns a single document.
2489              
2490             See the L documentation for details on the $projection and $options parameters.
2491              
2492             See also core documentation on querying:
2493             L.
2494              
2495             =head2 find_one_and_delete
2496              
2497             $doc = $coll->find_one_and_delete( $filter );
2498             $doc = $coll->find_one_and_delete( $filter, $options );
2499              
2500             Given a L, this deletes a document from
2501             the database and returns it as it appeared before it was deleted.
2502              
2503             A hash reference of options may be provided. Valid keys include:
2504              
2505             =over 4
2506              
2507             =item *
2508              
2509             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2510              
2511             =item *
2512              
2513             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2514              
2515             =item *
2516              
2517             C - a hash reference defining fields to return. See "L" in the MongoDB documentation for details.
2518              
2519             =item *
2520              
2521             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2522              
2523             =item *
2524              
2525             C – an L defining the order in which to return matching documents. See docs for L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
2526              
2527             =back
2528              
2529             =head2 find_one_and_replace
2530              
2531             $doc = $coll->find_one_and_replace( $filter, $replacement );
2532             $doc = $coll->find_one_and_replace( $filter, $replacement, $options );
2533              
2534             Given a L and a replacement document,
2535             this replaces a document from the database and returns it as it was either
2536             right before or right after the replacement. The default is 'before'.
2537              
2538             The replacement document must not have any field-update operators in it (e.g.
2539             C<$set>).
2540              
2541             A hash reference of options may be provided. Valid keys include:
2542              
2543             =over 4
2544              
2545             =item *
2546              
2547             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2548              
2549             =item *
2550              
2551             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2552              
2553             =item *
2554              
2555             C – the maximum amount of time in milliseconds to allow the command to run.
2556              
2557             =item *
2558              
2559             C - a hash reference defining fields to return. See "L" in the MongoDB documentation for details.
2560              
2561             =item *
2562              
2563             C – either the string C<'before'> or C<'after'>, to indicate whether the returned document should be the one before or after replacement. The default is C<'before'>.
2564              
2565             =item *
2566              
2567             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2568              
2569             =item *
2570              
2571             C – an L defining the order in which to return matching documents. See docs for L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
2572              
2573             =item *
2574              
2575             C – defaults to false; if true, a new document will be added if one is not found
2576              
2577             =back
2578              
2579             =head2 find_one_and_update
2580              
2581             $doc = $coll->find_one_and_update( $filter, $update );
2582             $doc = $coll->find_one_and_update( $filter, $update, $options );
2583              
2584             Given a L and a document of update
2585             operators, this updates a single document and returns it as it was either right
2586             before or right after the update. The default is 'before'.
2587              
2588             The update document must contain only field-update operators (e.g. C<$set>).
2589              
2590             A hash reference of options may be provided. Valid keys include:
2591              
2592             =over 4
2593              
2594             =item *
2595              
2596             C - 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+.
2597              
2598             =item *
2599              
2600             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2601              
2602             =item *
2603              
2604             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2605              
2606             =item *
2607              
2608             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2609              
2610             =item *
2611              
2612             C - a hash reference defining fields to return. See "L" in the MongoDB documentation for details.
2613              
2614             =item *
2615              
2616             C – either the string C<'before'> or C<'after'>, to indicate whether the returned document should be the one before or after replacement. The default is C<'before'>.
2617              
2618             =item *
2619              
2620             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2621              
2622             =item *
2623              
2624             C – an L defining the order in which to return matching documents. See docs for L<$orderby|http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.
2625              
2626             =item *
2627              
2628             C – defaults to false; if true, a new document will be added if one is not found
2629              
2630             =back
2631              
2632             =head2 watch
2633              
2634             Watches for changes on this collection-
2635              
2636             Perform an aggregation with an implicit initial C<$changeStream> stage
2637             and returns a L result which can be used to
2638             iterate over the changes in the collection. This functionality is
2639             available since MongoDB 3.6.
2640              
2641             my $stream = $collection->watch();
2642             my $stream = $collection->watch( \@pipeline );
2643             my $stream = $collection->watch( \@pipeline, \%options );
2644              
2645             while (1) {
2646              
2647             # This inner loop will only run until no more changes are
2648             # available.
2649             while (my $change = $stream->next) {
2650             # process $change
2651             }
2652             }
2653              
2654             The returned stream will not block forever waiting for changes. If you
2655             want to respond to changes over a longer time use C and
2656             regularly call C in a loop.
2657              
2658             B: Using this helper method is preferred to manually aggregating
2659             with a C<$changeStream> stage, since it will automatically resume when
2660             the connection was terminated.
2661              
2662             The optional first argument must be an array-ref of
2663             L
2664             documents. Each pipeline document must be a hash reference. Not all
2665             pipeline stages are supported after C<$changeStream>.
2666              
2667             The optional second argument is a hash reference with options:
2668              
2669             =over 4
2670              
2671             =item *
2672              
2673             C - The fullDocument to pass as an option to the C<$changeStream> stage. Allowed values: C, C. Defaults to C. When set to C, 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.
2674              
2675             =item *
2676              
2677             C - The logical starting point for this change stream. This value can be obtained from the C<_id> field of a document returned by L. Cannot be specified together with C
2678              
2679             =item *
2680              
2681             C - The maximum number of milliseconds for the server to wait before responding.
2682              
2683             =item *
2684              
2685             C - A L specifying at what point in time changes will start being watched. Cannot be specified together with C. Plain values will be coerced to L objects.
2686              
2687             =item *
2688              
2689             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2690              
2691             =back
2692              
2693             See L for more available options.
2694              
2695             See the L
2696             for general usage information on change streams.
2697              
2698             See the L
2699             for details on change streams.
2700              
2701             =head2 aggregate
2702              
2703             @pipeline = (
2704             { '$group' => { _id => '$state,' totalPop => { '$sum' => '$pop' } } },
2705             { '$match' => { totalPop => { '$gte' => 10 * 1000 * 1000 } } }
2706             );
2707              
2708             $result = $collection->aggregate( \@pipeline );
2709             $result = $collection->aggregate( \@pipeline, $options );
2710              
2711             Runs a query using the MongoDB 2.2+ aggregation framework and returns a
2712             L object.
2713              
2714             The first argument must be an array-ref of L
2715             pipeline|http://docs.mongodb.org/manual/core/aggregation-pipeline/> documents.
2716             Each pipeline document must be a hash reference.
2717              
2718             B: Some pipeline documents have ordered arguments, such as C<$sort>.
2719             Be sure to provide these argument using L. E.g.:
2720              
2721             { '$sort' => Tie::IxHash->new( age => -1, posts => 1 ) }
2722              
2723             A hash reference of options may be provided. Valid keys include:
2724              
2725             =over 4
2726              
2727             =item *
2728              
2729             C – if, true enables writing to temporary files.
2730              
2731             =item *
2732              
2733             C – the number of documents to return per batch.
2734              
2735             =item *
2736              
2737             C - skips document validation, if enabled. (Note, this will be ignored for servers before version 3.2.)
2738              
2739             =item *
2740              
2741             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2742              
2743             =item *
2744              
2745             C – if true, return a single document with execution information.
2746              
2747             =item *
2748              
2749             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2750              
2751             =item *
2752              
2753             C - An index to use for this aggregation. (Only compatible with servers above version 3.6.) For more information, see the other aggregate options here: L
2754              
2755             =item *
2756              
2757             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2758              
2759             =back
2760              
2761             B MongoDB 2.6+ added the '$out' pipeline operator. If this operator is
2762             used to write aggregation results directly to a collection, an empty result
2763             will be returned. Create a new collection> object to query the generated result
2764             collection. When C<$out> is used, the command is treated as a write operation
2765             and read preference is ignored.
2766              
2767             See L in the MongoDB manual
2768             for more information on how to construct aggregation queries.
2769              
2770             B The use of aggregation cursors is automatic based on your server
2771             version. However, if migrating a sharded cluster from MongoDB 2.4 to 2.6
2772             or later, you must upgrade your mongod servers first before your mongos
2773             routers or aggregation queries will fail. As a workaround, you may
2774             pass C<< cursor => undef >> as an option.
2775              
2776             =head2 count_documents
2777              
2778             $count = $coll->count_documents( $filter );
2779             $count = $coll->count_documents( $filter, $options );
2780              
2781             Returns a count of documents matching a L.
2782             To return a count of all documents, use an empty hash reference as the filter.
2783              
2784             B: this may result in a scan of all documents in the collection.
2785             For a fast count of the total documents in a collection see
2786             L instead.
2787              
2788             A hash reference of options may be provided. Valid keys include:
2789              
2790             =over 4
2791              
2792             =item *
2793              
2794             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2795              
2796             =item *
2797              
2798             C – specify an index to use; must be a string, array reference, hash reference or L object. (Requires server version 3.6 or later.)
2799              
2800             =item *
2801              
2802             C – the maximum number of documents to count.
2803              
2804             =item *
2805              
2806             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2807              
2808             =item *
2809              
2810             C – the number of documents to skip before counting documents.
2811              
2812             =item *
2813              
2814             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2815              
2816             =back
2817              
2818             B: When upgrading from the deprecated C method, some legacy
2819             operators are not supported and must be replaced:
2820              
2821             +-------------+--------------------------------+
2822             | Legacy | Modern Replacement |
2823             +=============+================================+
2824             | $where | $expr (Requires MongoDB 3.6+) |
2825             +-------------+--------------------------------+
2826             | $near | $geoWithin with $center |
2827             +-------------+--------------------------------+
2828             | $nearSphere | $geoWithin with $centerSphere |
2829             +-------------+--------------------------------+
2830              
2831             =head2 estimated_document_count
2832              
2833             $count = $coll->estimated_document_count();
2834             $count = $coll->estimated_document_count($options);
2835              
2836             Returns an estimated count of documents based on collection metadata.
2837              
2838             B: this method does not support sessions or transactions.
2839              
2840             A hash reference of options may be provided. Valid keys include:
2841              
2842             =over 4
2843              
2844             =item *
2845              
2846             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2847              
2848             =back
2849              
2850             =head2 distinct
2851              
2852             $result = $coll->distinct( $fieldname );
2853             $result = $coll->distinct( $fieldname, $filter );
2854             $result = $coll->distinct( $fieldname, $filter, $options );
2855              
2856             Returns a L object that will provide distinct values for
2857             a specified field name.
2858              
2859             The query may be limited by an optional L
2860             expression>.
2861              
2862             A hash reference of options may be provided. Valid keys include:
2863              
2864             =over 4
2865              
2866             =item *
2867              
2868             C - a L defining the collation for this operation. See docs for the format of the collation document here: L.
2869              
2870             =item *
2871              
2872             C – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
2873              
2874             =item *
2875              
2876             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2877              
2878             =back
2879              
2880             See documentation for the L
2881             command|http://docs.mongodb.org/manual/reference/command/distinct/> for
2882             details.
2883              
2884             =head2 rename
2885              
2886             $newcollection = $collection->rename("mynewcollection");
2887              
2888             Renames the collection. If a collection already exists with the new collection
2889             name, this method will throw an exception.
2890              
2891             A hashref of options may be provided.
2892              
2893             Valid options include:
2894              
2895             =over 4
2896              
2897             =item *
2898              
2899             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
2900              
2901             =back
2902              
2903             It returns a new L object corresponding to the renamed
2904             collection.
2905              
2906             =head2 drop
2907              
2908             $collection->drop;
2909              
2910             Deletes a collection as well as all of its indexes.
2911              
2912             =head2 ordered_bulk
2913              
2914             $bulk = $coll->ordered_bulk;
2915             $bulk->insert_one( $doc1 );
2916             $bulk->insert_one( $doc2 );
2917             ...
2918             $result = $bulk->execute;
2919              
2920             Returns a L object to group write operations into fewer network
2921             round-trips. This method creates an B operation, where operations halt after
2922             the first error. See L for more details.
2923              
2924             The method C may be used as an alias.
2925              
2926             A hash reference of options may be provided.
2927              
2928             Valid options include:
2929              
2930             =over 4
2931              
2932             =item *
2933              
2934             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2935              
2936             =back
2937              
2938             =head2 unordered_bulk
2939              
2940             This method works just like L except that the order that
2941             operations are sent to the database is not guaranteed and errors do not halt processing.
2942             See L for more details.
2943              
2944             The method C may be used as an alias.
2945              
2946             A hash reference of options may be provided.
2947              
2948             Valid options include:
2949              
2950             =over 4
2951              
2952             =item *
2953              
2954             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
2955              
2956             =back
2957              
2958             =head2 bulk_write
2959              
2960             $res = $coll->bulk_write( [ @requests ], $options )
2961              
2962             This method provides syntactic sugar to construct and execute a bulk operation
2963             directly, without using C or
2964             C to generate a L object and
2965             then calling methods on it. It returns a L object
2966             just like the L method.
2967              
2968             The first argument must be an array reference of requests. Requests consist
2969             of pairs of a MongoDB::Collection write method name (e.g. C,
2970             C) and an array reference of arguments to the corresponding
2971             method name. They may be given as pairs, or as hash or array
2972             references:
2973              
2974             # pairs -- most efficient
2975             @requests = (
2976             insert_one => [ { x => 1 } ],
2977             replace_one => [ { x => 1 }, { x => 4 } ],
2978             delete_one => [ { x => 4 } ],
2979             update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ],
2980             );
2981              
2982             # hash references
2983             @requests = (
2984             { insert_one => [ { x => 1 } ] },
2985             { replace_one => [ { x => 1 }, { x => 4 } ] },
2986             { delete_one => [ { x => 4 } ] },
2987             { update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] },
2988             );
2989              
2990             # array references
2991             @requests = (
2992             [ insert_one => [ { x => 1 } ] ],
2993             [ replace_one => [ { x => 1 }, { x => 4 } ] ],
2994             [ delete_one => [ { x => 4 } ] ],
2995             [ update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] ],
2996             );
2997              
2998             Valid method names include C, C, C,
2999             C C, C, C.
3000              
3001             An optional hash reference of options may be provided.
3002              
3003             Valid options include:
3004              
3005             =over 4
3006              
3007             =item *
3008              
3009             C - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
3010              
3011             =item *
3012              
3013             C – when true, the bulk operation is executed like L. When false, the bulk operation is executed like L. The default is true.
3014              
3015             =item *
3016              
3017             C - the session to use for these operations. If not supplied, will use an implicit session. For more information see L
3018              
3019             =back
3020              
3021             See L for more details on bulk writes. Be advised that
3022             the legacy Bulk API method names differ slightly from MongoDB::Collection
3023             method names.
3024              
3025             =for Pod::Coverage count
3026             initialize_ordered_bulk_op
3027             initialize_unordered_bulk_op
3028             batch_insert
3029             find_and_modify
3030             insert
3031             query
3032             remove
3033             update
3034              
3035             =head1 AUTHORS
3036              
3037             =over 4
3038              
3039             =item *
3040              
3041             David Golden
3042              
3043             =item *
3044              
3045             Rassi
3046              
3047             =item *
3048              
3049             Mike Friedman
3050              
3051             =item *
3052              
3053             Kristina Chodorow
3054              
3055             =item *
3056              
3057             Florian Ragwitz
3058              
3059             =back
3060              
3061             =head1 COPYRIGHT AND LICENSE
3062              
3063             This software is Copyright (c) 2020 by MongoDB, Inc.
3064              
3065             This is free software, licensed under:
3066              
3067             The Apache License, Version 2.0, January 2004
3068              
3069             =cut
3070              
3071             __END__