This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
/
Collection.pm
1011 lines (728 loc) · 28.3 KB
/
Collection.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2009-2013 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package MongoDB::Collection;
# ABSTRACT: A MongoDB Collection
use version;
our $VERSION = 'v0.703.5'; # TRIAL
use Tie::IxHash;
use Moose;
use Carp 'carp';
use boolean;
use Devel::Size 'total_size';
use Try::Tiny;
has _database => (
is => 'ro',
isa => 'MongoDB::Database',
required => 1,
);
has name => (
is => 'ro',
isa => 'Str',
required => 1,
);
has full_name => (
is => 'ro',
isa => 'Str',
lazy => 1,
builder => '_build_full_name',
);
sub _build_full_name {
my ($self) = @_;
my $name = $self->name;
my $db_name = $self->_database->name;
return "${db_name}.${name}";
}
sub get_collection {
my $self = shift @_;
my $coll = shift @_;
return $self->_database->get_collection($self->name.'.'.$coll);
}
sub to_index_string {
my $keys = shift;
my @name;
if (ref $keys eq 'ARRAY') {
@name = @$keys;
}
elsif (ref $keys eq 'HASH' ) {
@name = %$keys
}
elsif (ref $keys eq 'Tie::IxHash') {
my @ks = $keys->Keys;
my @vs = $keys->Values;
for (my $i=0; $i<$keys->Length; $i++) {
push @name, $ks[$i];
push @name, $vs[$i];
}
}
else {
confess 'expected Tie::IxHash, hash, or array reference for keys';
}
return join("_", @name);
}
sub _select_cursor_client {
my ($conn, $ns, $query) = @_;
return $conn if !$conn->_readpref_pinned || !$conn->find_master;
return $conn->_master if _cmd_primary_only($ns, $query);
return $conn->_readpref_pinned;
}
sub _cmd_primary_only {
my ($ns, $query) = @_;
# these commands allow read preferences
my %readpref_commands = (
'group' => 1,
'aggregate' => 1,
'mapreduce' => 1,
'collstats' => 1,
'dbstats' => 1,
'count' => 1,
'distinct' => 1,
'geonear' => 1,
'geosearch' => 1,
'geowalk' => 1,
'text' => 1
);
if ($ns =~ /\$cmd/) {
foreach (keys %{$query}) {
return 0 if $readpref_commands{lc($_)};
}
return 1;
}
else {
return 0;
}
}
sub find {
my ($self, $query, $attrs) = @_;
# old school options - these should be set with MongoDB::Cursor methods
my ($limit, $skip, $sort_by) = @{ $attrs || {} }{qw/limit skip sort_by/};
$limit ||= 0;
$skip ||= 0;
my $conn = $self->_database->_client;
my $q = $query || {};
my $ns = $self->full_name;
my $slave_ok = ($conn->_readpref_mode == MongoDB::MongoClient->PRIMARY) ||
_cmd_primary_only($ns, $q)
? 0 : 1;
my $cursor = MongoDB::Cursor->new(
_master => $conn,
_client => _select_cursor_client($conn, $ns, $q),
_ns => $ns,
_query => $q,
_limit => $limit,
_skip => $skip,
slave_okay => $slave_ok
);
# add readpref info if connected to mongos
if ($conn->_readpref_pinned && $conn->_is_mongos && !_cmd_primary_only($ns, $q)) {
my $modeName = MongoDB::MongoClient->_READPREF_MODENAMES->[$conn->_readpref_mode];
$cursor->_add_readpref({mode => $modeName, tags => $conn->_readpref_tagsets});
}
$cursor->_init;
if ($sort_by) {
$cursor->sort($sort_by);
}
return $cursor;
}
sub query {
my ($self, $query, $attrs) = @_;
return $self->find($query, $attrs);
}
sub find_one {
my ($self, $query, $fields) = @_;
$query ||= {};
$fields ||= {};
return $self->find($query)->limit(-1)->fields($fields)->next;
}
sub _split_batch {
my ( $self, $docs ) = @_;
# this will give us a rather inflated size as compared to the BSON
# serialized version of the structure, so we'll use it as a rather
# liberal estimate of when to split the batch.
my $size = total_size $docs;
return $docs if $size < 16_777_216;
my ( @left, @right );
@left = @{$docs}[ 0 .. int( @$docs / 2 ) - 1];
@right = @{$docs}[ int( @$docs / 2 ) .. $#$docs ];
return ( total_size \@left < 16_777_216 ? \@left : $self->_split_batch( \@left ),
total_size \@right < 16_777_216 ? \@right : $self->_split_batch( \@right ) );
}
sub insert {
my $self = shift;
my ( $object, $options ) = @_;
$self->legacy_insert( @_ );
}
sub legacy_insert {
my ($self, $object, $options) = @_;
my ($id) = $self->batch_insert( [ $object ], $options);
return $id;
}
sub batch_insert {
my ($self, $object, $options) = @_;
confess 'not an array reference' unless ref $object eq 'ARRAY';
my $add_ids = 1;
if ($options->{'no_ids'}) {
$add_ids = 0;
}
my $conn = $self->_database->_client;
my $ns = $self->full_name;
my ($insert, $ids) = MongoDB::write_insert($ns, $object, $add_ids);
if (length($insert) > $conn->max_bson_size) {
Carp::croak("insert is too large: ".length($insert)." max: ".$conn->max_bson_size);
return 0;
}
if ( ( defined($options) && $options->{safe} ) or $conn->_w_want_safe ) {
my $ok = $self->_make_safe($insert);
if (!$ok) {
return 0;
}
}
else {
$conn->send($insert);
}
return $ids ? @$ids : $ids;
}
sub update {
my $self = shift;
my ( $query, $object, $opts ) = @_;
return $self->legacy_update( @_ );
}
sub legacy_update {
my ($self, $query, $object, $opts) = @_;
#$self->update_cmd( $query, $object, $opts ) if $self->_database->_client->_use_write_cmd;
# there used to be one option: upsert=0/1
# now there are two, there will probably be
# more in the future. So, to support old code,
# passing "1" will still be supported, but not
# documentd, so we can phase that out eventually.
#
# The preferred way of passing options will be a
# hash of {optname=>value, ...}
my $flags = 0;
if ($opts && ref $opts eq 'HASH') {
$flags |= $opts->{'upsert'} << 0
if exists $opts->{'upsert'};
$flags |= $opts->{'multiple'} << 1
if exists $opts->{'multiple'};
}
else {
$flags = !(!$opts);
}
my $conn = $self->_database->_client;
my $ns = $self->full_name;
my $update = MongoDB::write_update($ns, $query, $object, $flags);
if ($opts->{safe} or $conn->_w_want_safe ) {
return $self->_make_safe($update);
}
if ($conn->send($update) == -1) {
$conn->connect;
die("can't get db response, not connected");
}
return 1;
}
sub find_and_modify {
my ( $self, $opts ) = @_;
my $conn = $self->_database->_client;
my $db = $self->_database;
my $result;
try {
$result = $db->_try_run_command( [ findAndModify => $self->name, %$opts ] )
}
catch {
die $_ unless $_ eq 'No matching object found';
};
return $result->{value} if $result;
return;
}
sub aggregate {
my ( $self, $pipeline, $opts ) = @_;
$opts = ref $opts eq 'HASH' ? $opts : { };
my $db = $self->_database;
if ( exists $opts->{cursor} ) {
$opts->{cursor} = { } unless ref $opts->{cursor} eq 'HASH';
}
# explain requires a boolean
if ( exists $opts->{explain} ) {
$opts->{explain} = $opts->{explain} ? true : false;
}
my @command = ( aggregate => $self->name, pipeline => $pipeline, %$opts );
my $result = $db->_try_run_command( \@command );
# if we got a cursor option then we need to construct a wonky cursor
# object on our end and populate it with the first batch, since
# commands can't actually return cursors.
if ( exists $opts->{cursor} ) {
unless ( exists $result->{cursor} ) {
die "no cursor returned from aggregation";
}
my $cursor = MongoDB::Cursor->new(
started_iterating => 1, # we have the first batch
_client => $db->_client,
_master => $db->_client, # fake this because we're already iterating
_ns => $result->{cursor}{ns},
_agg_first_batch => $result->{cursor}{firstBatch},
_agg_batch_size => scalar @{ $result->{cursor}{firstBatch} }, # for has_next
_query => \@command,
);
$cursor->_init( $result->{cursor}{id} );
return $cursor;
}
# return the whole result document if they want an explain
if ( $opts->{explain} ) {
return $result;
}
# TODO: handle errors?
return $result->{result};
}
sub parallel_scan {
my ( $self, $num_cursors, $opts ) = @_;
unless (defined $num_cursors && $num_cursors == int($num_cursors)
&& $num_cursors > 0 && $num_cursors <= 10000
) {
Carp::croak( "first argument to parallel_scan must be a positive integer between 1 and 10000" )
}
$opts = ref $opts eq 'HASH' ? $opts : { };
my $db = $self->_database;
my @command = ( parallelCollectionScan => $self->name, numCursors => $num_cursors );
my $result = $db->_try_run_command( \@command );
Carp::croak("No cursors returned")
unless $result->{cursors} && ref $result->{cursors} eq 'ARRAY';
my @cursors;
for my $c ( map { $_->{cursor} } @{$result->{cursors}} ) {
# fake up a post-query cursor
my $cursor = MongoDB::Cursor->new(
started_iterating => 1, # we have the first batch
_client => $db->_client,
_master => $db->_client, # fake this because we're already iterating
_ns => $c->{ns},
_query => \@command,
_is_parallel => 1,
);
$cursor->_init( $c->{id} );
push @cursors, $cursor;
}
return @cursors;
}
sub rename {
my ($self, $collectionname) = @_;
my $conn = $self->_database->_client;
my $database = $conn->get_database( 'admin' );
my $fullname = $self->full_name;
my ($db, @collection_bits) = split(/\./, $fullname);
my $collection = join('.', @collection_bits);
my $obj = $database->_try_run_command([ 'renameCollection' => "$db.$collection", 'to' => "$db.$collectionname" ]);
return $conn->get_database( $db )->get_collection( $collectionname );
}
sub remove {
my $self = shift;
my ( $query, $options ) = @_;
$self->legacy_remove( @_ );
}
sub legacy_remove {
my ($self, $query, $options) = @_;
#$self->delete_cmd( $query, $options ) if $self->_database->_client->_use_write_cmd;
my $conn = $self->_database->_client;
my ($just_one, $safe);
if (defined $options && ref $options eq 'HASH') {
$just_one = exists $options->{just_one} ? $options->{just_one} : 0;
$safe = $options->{safe} or $conn->_w_want_safe;
}
else {
$just_one = $options || 0;
}
my $ns = $self->full_name;
$query ||= {};
my $remove = MongoDB::write_remove($ns, $query, $just_one);
if ($safe) {
return $self->_make_safe($remove);
}
if ($conn->send($remove) == -1) {
$conn->connect;
die("can't get db response, not connected");
}
return 1;
}
sub ensure_index {
my ($self, $keys, $options, $garbage) = @_;
my $ns = $self->full_name;
# we need to use the crappy old api if...
# - $options isn't a hash, it's a string like "ascending"
# - $keys is a one-element array: [foo]
# - $keys is an array with more than one element and the second
# element isn't a direction (or at least a good one)
# - Tie::IxHash has values like "ascending"
if (($options && ref $options ne 'HASH') ||
(ref $keys eq 'ARRAY' &&
($#$keys == 0 || $#$keys >= 1 && !($keys->[1] =~ /-?1/))) ||
(ref $keys eq 'Tie::IxHash' && $keys->[2][0] =~ /(de|a)scending/)) {
Carp::croak("you're using the old ensure_index format, please upgrade");
}
$keys = Tie::IxHash->new(@$keys) if ref $keys eq 'ARRAY';
my $obj = Tie::IxHash->new("ns" => $ns, "key" => $keys);
if (exists $options->{name}) {
$obj->Push("name" => $options->{name});
}
else {
$obj->Push("name" => MongoDB::Collection::to_index_string($keys));
}
foreach ("unique", "background", "sparse") {
if (exists $options->{$_}) {
$obj->Push("$_" => ($options->{$_} ? boolean::true : boolean::false));
}
}
if (exists $options->{drop_dups}) {
$obj->Push("dropDups" => ($options->{drop_dups} ? boolean::true : boolean::false));
}
$options->{'no_ids'} = 1;
foreach ("weights", "default_language", "language_override") {
if (exists $options->{$_}) {
$obj->Push("$_" => $options->{$_});
}
}
if (exists $options->{expire_after_seconds}) {
$obj->Push("expireAfterSeconds" => int($options->{expire_after_seconds}));
}
my ($db, $coll) = $ns =~ m/^([^\.]+)\.(.*)/;
# try the new createIndexes command (mongodb 2.6), falling back to the old insert
# method if createIndexes is not available.
my $tmp_ns = $obj->DELETE( 'ns' ); # ci command takes ns outside of index spec
my $res = $self->_database->get_collection( '$cmd' )->find_one( Tie::IxHash->new( createIndexes => $self->name, indexes => [ $obj ] ) );
return $res if $res->{ok};
if ( ( not $res->{ok} ) &&
( not exists $res->{code} or $res->{code} == 59 ) ) {
$obj->Unshift( ns => $tmp_ns ); # restore ns to spec
my $indexes = $self->_database->get_collection("system.indexes");
return $indexes->insert($obj, $options);
} else {
die "error creating index: " . $res->{errmsg};
}
}
sub _make_safe {
my ($self, $req) = @_;
my $conn = $self->_database->_client;
my $db = $self->_database->name;
my $last_error = Tie::IxHash->new(getlasterror => 1, w => $conn->w, wtimeout => $conn->wtimeout, j => $conn->j);
my ($query, $info) = MongoDB::write_query($db.'.$cmd', 0, 0, -1, $last_error);
$conn->send("$req$query");
my $cursor = MongoDB::Cursor->new(_ns => $info->{ns},
_master => $conn,
_client => $conn,
_query => {});
$cursor->_init;
$cursor->_request_id($info->{'request_id'});
$conn->recv($cursor);
$cursor->started_iterating(1);
my $ok = $cursor->next();
# $ok->{ok} is 1 if err is set
Carp::croak $ok->{err} if $ok->{err};
# $ok->{ok} == 0 is still an error
if (!$ok->{ok}) {
Carp::croak $ok->{errmsg};
}
return $ok;
}
sub save {
my ($self, $doc, $options) = @_;
if (exists $doc->{"_id"}) {
if (!$options || !ref $options eq 'HASH') {
$options = {"upsert" => boolean::true};
}
else {
$options->{'upsert'} = boolean::true;
}
return $self->update({"_id" => $doc->{"_id"}}, $doc, $options);
}
else {
return $self->insert($doc, $options);
}
}
sub count {
my ($self, $query) = @_;
$query ||= {};
my $obj;
try {
$obj = $self->_database->_try_run_command([
count => $self->name,
query => $query,
]);
}
catch {
# if there was an error, check if it was the "ns missing" one that means the
# collection hasn't been created or a real error.
die $_ unless /^ns missing/;
};
return $obj ? $obj->{n} : 0;
}
sub validate {
my ($self, $scan_data) = @_;
$scan_data = 0 unless defined $scan_data;
my $obj = $self->_database->run_command({ validate => $self->name });
}
sub drop_indexes {
my ($self) = @_;
return $self->drop_index('*');
}
sub drop_index {
my ($self, $index_name) = @_;
return $self->_database->run_command([
dropIndexes => $self->name,
index => $index_name,
]);
}
sub get_indexes {
my ($self) = @_;
return $self->_database->get_collection('system.indexes')->query({
ns => $self->full_name,
})->all;
}
sub drop {
my ($self) = @_;
$self->_database->run_command({ drop => $self->name });
return;
}
sub bulk {
my ( $self, %args ) = @_;
return MongoDB::Bulk->new( %args, collection => $self );
}
__PACKAGE__->meta->make_immutable;
1;
__END__
=pod
=head1 SYNOPSIS
An instance of a MongoDB collection.
# gets the foo collection
my $collection = $db->get_collection( 'foo' );
Collection names can be chained together to access subcollections. For
instance, the collection C<foo.bar> can be accessed with either:
my $collection = $db->get_collection( 'foo' )->get_collection( 'bar' );
or
my $collection = $db->get_collection( 'foo.bar' );
=attr name
The name of the collection.
=attr full_name
The full_name of the collection, including the namespace of the database it's
in.
=method get_collection ($name)
my $collection = $database->get_collection('foo');
Returns a L<MongoDB::Collection> for the collection called C<$name> within this
collection.
=method find($query)
my $cursor = $collection->find({ i => { '$gt' => 42 } });
Executes the given C<$query> and returns a C<MongoDB::Cursor> with the results.
C<$query> can be a hash reference, L<Tie::IxHash>, or array reference (with an
even number of elements).
The set of fields returned can be limited through the use of the
C<MongoDB::Cursor::fields> method on the resulting L<MongoDB::Cursor> object.
Other commonly used cursor methods are C<MongoDB::Cursor::limit>,
C<MongoDB::Cursor::skip>, and C<MongoDB::Cursor::sort>.
See also core documentation on querying:
L<http://docs.mongodb.org/manual/core/read/>.
=method query($query, $attrs?)
Identical to C<MongoDB::Collection::find>, described above.
my $cursor = $collection->query->limit(10)->skip(10);
my $cursor = $collection->query({ location => "Vancouver" })->sort({ age => 1 });
Valid query attributes are:
=over 4
=item limit
Limit the number of results.
=item skip
Skip a number of results.
=item sort_by
Order results.
=back
=method find_one($query, $fields?)
my $object = $collection->find_one({ name => 'Resi' });
my $object = $collection->find_one({ name => 'Resi' }, { name => 1, age => 1});
Executes the given C<$query> and returns the first object matching it.
C<$query> can be a hash reference, L<Tie::IxHash>, or array reference (with an
even number of elements). If C<$fields> is specified, the resulting document
will only include the fields given (and the C<_id> field) which can cut down on
wire traffic.
=method insert ($object, $options?)
my $id1 = $coll->insert({ name => 'mongo', type => 'database' });
my $id2 = $coll->insert({ name => 'mongo', type => 'database' }, {safe => 1});
Inserts the given C<$object> into the database and returns it's id
value. C<$object> can be a hash reference, a reference to an array with an
even number of elements, or a L<Tie::IxHash>. The id is the C<_id> value
specified in the data or a L<MongoDB::OID>.
The optional C<$options> parameter can be used to specify if this is a safe
insert. A safe insert will check with the database if the insert succeeded and
croak if it did not. You can also check if the insert succeeded by doing an
unsafe insert, then calling L<MongoDB::Database/"last_error($options?)">.
See also core documentation on insert: L<http://docs.mongodb.org/manual/core/create/>.
=method batch_insert (\@array, $options)
my @ids = $collection->batch_insert([{name => "Joe"}, {name => "Fred"}, {name => "Sam"}]);
Inserts each of the documents in the array into the database and returns an
array of their _id fields.
The optional C<$options> parameter can be used to specify if this is a safe
insert. A safe insert will check with the database if the insert succeeded and
croak if it did not. You can also check if the inserts succeeded by doing an
unsafe batch insert, then calling L<MongoDB::Database/"last_error($options?)">.
=method update (\%criteria, \%object, \%options?)
$collection->update({'x' => 3}, {'$inc' => {'count' => -1} }, {"upsert" => 1, "multiple" => 1});
Updates an existing C<$object> matching C<$criteria> in the database.
Returns 1 unless the C<safe> option is set. If C<safe> is set, this will return
a hash of information about the update, including number of documents updated
(C<n>). If C<safe> is set and the update fails, C<update> will croak. You can
also check if the update succeeded by doing an unsafe update, then calling
L<MongoDB::Database/"last_error($options?)">.
C<update> can take a hash reference of options. The options currently supported
are:
=over
=item C<upsert>
If no object matching C<$criteria> is found, C<$object> will be inserted.
=item C<multiple>
All of the documents that match C<$criteria> will be updated, not just
the first document found. (Only available with database version 1.1.3 and
newer.)
=item C<safe>
If the update fails and safe is set, the update will croak.
=back
See also core documentation on update: L<http://docs.mongodb.org/manual/core/update/>.
=method find_and_modify
my $result = $collection->find_and_modify( { query => { ... }, update => { ... } } );
Perform an atomic update. C<find_and_modify> guarantees that nothing else will come along
and change the queried documents before the update is performed.
Returns the old version of the document, unless C<new => 1> is specified. If no documents
match the query, it returns nothing.
=method aggregate
my $result = $collection->aggregate( [ ... ] );
Run a query using the MongoDB 2.2+ aggregation framework. The first argument is an array-ref of
aggregation pipeline operators.
The type of return value from C<aggregate> depends on how you use it.
=over 4
=item * By default, the aggregation framework returns a document with an embedded array of results, and
the C<aggregate> method returns a reference to that array.
=item * MongoDB 2.6+ supports returning cursors from aggregation queries, allowing you to bypass
the 16MB size limit of documents. If you specifiy a C<cursor> option, the C<aggregate> method
will return a L<MongoDB::Cursor> object which can be iterated in the normal fashion.
my $cursor = $collection->aggregate( [ ... ], { cursor => 1 } );
Specifying a C<cursor> option will cause an error on versions of MongoDB below 2.6.
The C<cursor> option may also have some useful options of its own. Currently, the only one
is C<batchSize>, which allows you to control how frequently the cursor must go back to the
database for more documents.
my $cursor = $collection->aggregate( [ ... ], { cursor => { batchSize => 10 } } );
=item * MongoDB 2.6+ supports an C<explain> option to aggregation queries to retrieve data
about how the server will process a query pipeline.
my $result = $collection->aggregate( [ ... ], { explain => 1 } );
In this case, C<aggregate> will return a document (not an array) containing the explanation
structure.
=item * Finally, MongoDB 2.6+ will return an empty results array if the C<$out> pipeline operator is used to
write aggregation results directly to a collection. Create a new C<Collection> object to
query the result collection.
=back
See L<Aggregation|http://docs.mongodb.org/manual/aggregation/> in the MongoDB manual
for more information on how to construct aggregation queries.
=method parallel_scan($max_cursors)
my @cursors = $collection->parallel_scan(10);
Scan the collection in parallel. The argument is the maximum number of
L<MongoDB::Cursor> objects to return and must be a positive integer between 1
and 10,000.
As long as the collection is not modified during scanning, each document will
appear only once in one of the cursors' result sets.
Only iteration methods may be called on parallel scan cursors.
If an error occurs, an exception will be thrown.
=method rename ("newcollectionname")
my $newcollection = $collection->rename("mynewcollection");
Renames the collection. It expects that the new name is currently not in use.
Returns the new collection. If a collection already exists with that new collection name this will
die.
=method save($doc, $options)
$collection->save({"author" => "joe"});
my $post = $collection->find_one;
$post->{author} = {"name" => "joe", "id" => 123, "phone" => "555-5555"};
$collection->save( $post );
$collection->save( $post, { safe => 1 } )
Inserts a document into the database if it does not have an _id field, upserts
it if it does have an _id field.
The return types for this function are a bit of a mess, as it will return the
_id if a new document was inserted, 1 if an upsert occurred, and croak if the
safe option was set and an error occurred. You can also check if the save
succeeded by doing an unsafe save, then calling
L<MongoDB::Database/"last_error($options?)">.
=method remove ($query?, $options?)
$collection->remove({ answer => { '$ne' => 42 } });
Removes all objects matching the given C<$query> from the database. If no
parameters are given, removes all objects from the collection (but does not
delete indexes, as C<MongoDB::Collection::drop> does).
Returns 1 unless the C<safe> option is set. If C<safe> is set and the remove
succeeds, C<remove> will return a hash of information about the remove,
including how many documents were removed (C<n>). If the remove fails and
C<safe> is set, C<remove> will croak. You can also check if the remove
succeeded by doing an unsafe remove, then calling
L<MongoDB::Database/"last_error($options?)">.
C<remove> can take a hash reference of options. The options currently supported
are
=over
=item C<just_one>
Only one matching document to be removed.
=item C<safe>
If the update fails and safe is set, this function will croak.
=back
See also core documentation on remove: L<http://docs.mongodb.org/manual/core/delete/>.
=method ensure_index ($keys, $options?)
use boolean;
$collection->ensure_index({"foo" => 1, "bar" => -1}, { unique => true });
Makes sure the given C<$keys> of this collection are indexed. C<$keys> can be an
array reference, hash reference, or C<Tie::IxHash>. C<Tie::IxHash> is preferred
for multi-key indexes, so that the keys are in the correct order. 1 creates an
ascending index, -1 creates a descending index.
If the C<safe> option is not set, C<ensure_index> will not return anything
unless there is a socket error (in which case it will croak). If the C<safe>
option is set and the index creation fails, it will also croak. You can also
check if the indexing succeeded by doing an unsafe index creation, then calling
L<MongoDB::Database/"last_error($options?)">.
See the L<MongoDB::Indexing> pod for more information on indexing.
=method count($query?)
my $n_objects = $collection->count({ name => 'Bob' });
Counts the number of objects in this collection that match the given C<$query>.
If no query is given, the total number of objects in the collection is returned.
=method validate
$collection->validate;
Asks the server to validate this collection.
Returns a hash of the form:
{
'ok' => '1',
'ns' => 'foo.bar',
'result' => info
}
where C<info> is a string of information
about the collection.
=method drop_indexes
$collection->drop_indexes;
Removes all indexes from this collection.
=method drop_index ($index_name)
$collection->drop_index('foo_1');
Removes an index called C<$index_name> from this collection.
Use C<MongoDB::Collection::get_indexes> to find the index name.
=method get_indexes
my @indexes = $collection->get_indexes;
Returns a list of all indexes of this collection.
Each index contains C<ns>, C<name>, and C<key>
fields of the form:
{
'ns' => 'db_name.collection_name',
'name' => 'index_name',
'key' => {
'key1' => dir1,
'key2' => dir2,
...
'keyN' => dirN
}
}