/
Collection.pod6
486 lines (336 loc) · 14.9 KB
/
Collection.pod6
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
use v6;
=begin pod
=TITLE class MongoDB::Collection
=SUBTITLE Operations on collections in a MongoDB database
unit package MongoDB;
class Collection { ... }
=head1 Synopsis
# Initialize
my MongoDB::Client $client .= new(:uri('mongodb://'));
my MongoDB::Database $database = $client.database('contacts');
my MongoDB::Collection $collection = $database.collection('perl_users');
# Find everything
for $collection.find -> BSON::Document $document {
$document.perl.say;
}
# Or narrow down using conditions.
my MongoDB::Cursor $cursor = $collection.find(
:$criteria(nick => 'camelia'), $number-to-return(1)
);
$cursor.fetch.perl.say;
Class to help accessing and manipulating collections in MongoDB databases.
=head1 Readonly attributes
=head2 database
has DatabaseType $.database;
Get the database object of this collection. It is set by
MongoDB::Database when a collection object is created.
=head2 name
has Str $.name;
Get the name of the current collection. It is set by C<MongoDB::Database> when a
collection object is created.
=head2 full-collection-name
has Str $.full-collection-name;
Get the full representation of this collection. This is a string composed of
the database name and collection name separated by a dot. E.g. I<person.address>
means collection I<address> in database I<person>.
=head1 Methods
=head2 new
submethod BUILD ( DatabaseType:D :$database, Str:D :$name )
Example
my MongoDB::Database $database .= new( :$client, :name<contacts>);
my MongoDB::Collection $collection .= new( :$database, :name<perl_users>);
Creates a new Collection object. However, it is better to call collection on
the database or client object as shown here;
my MongoDB::Database $database = $client.database('contacts');
my MongoDB::Collection $collection = $database.collection('perl_users');
or
my MongoDB::Collection $collection = $client.collection('contacts.perl_users');
my MongoDB::Database $database = $collection.database;
=head2 find
multi method find (
List :$criteria where all(@$criteria) ~~ Pair = (),
List :$projection where all(@$projection) ~~ Pair = (),
Int :$number-to-skip = 0, Int :$number-to-return = 0,
QueryFindFlags :@flags = Array[QueryFindFlags].new,
--> MongoDB::Cursor
)
Call method find using lists of pairs. An example;
my MongoDB::Cursor $c = $collection.find(
:criteria(nick => 'MARTIMM',), :projection(_id => 0,)
);
Mind the comma's! When only one pair is entered in the list, it is coerced to
a pair instead of a list of pairs.
multi method find (
BSON::Document :$criteria = BSON::Document.new,
BSON::Document :$projection?,
Int :$number-to-skip = 0, Int :$number-to-return = 0,
QueryFindFlags :@flags = Array[QueryFindFlags].new,
--> MongoDB::Cursor
)
Call method find using the BSON::Document class.
my MongoDB::Cursor $c = $collection.find(
:criteria( BSON::Document.new( nick => 'MARTIMM',)),
:projection( BSON::Document.new( _id => 0,))
);
Find documents in the database. When C<$criteria> is not provided all documents
are returned. There are 2 options and some flags to affect the search.
C<$projection> is used to select the fields to be returned. It looks like B<<(field
=> 1,)>> or B<<(field => 0,)>>. When 1 the field is included, when 0 it will be
excluded. The _id field is always included unless explicitly excluded like
B<<(_id => 0,)>>. The method returns a C<MongoDB::Cursor>.
=begin item1
B<:number-to-skip>. Sets the number of documents to omit - starting from the
first document in the resulting dataset - when returning the result of the
query.
=end item1
=begin item1
B<:number-to-return>. Limits the number of documents in the first OP_REPLY
message to the query. However, the database will still establish a cursor and
return the cursorID to the client if there are more results than
number-to-return. If number-to-return is 0, the db will use the default return
size. If the number is negative, then the database will return that number and
close the cursor. No further results for that query can be fetched. If
number-to-return is 1 the server will treat it as -1 (closing the cursor
automatically).
=end item1
=begin item1
B<:flags>. This is an array variable which is filled with C<QueryFindFlags>
values defined in C<MongoDB>. An example;
my $c = $collection.find(
:flags(Array[QueryFindFlags].new(C-QF-SLAVEOK))
);
or
my QueryFindFlags @flags = C-QF-SLAVEOK, C-QF-TAILABLECURSOR;
my $c = $collection.find(:@flags);
First example looks complex but that might change in the future, this is the
situation at 2016-11-9 with rakudo version 2016.10-249-gb84158c built on MoarVM
version 2016.10-37-gf769569 implementing Perl 6.c.
=end item1
=begin item2
B<C-QF-TAILABLECURSOR>: corresponds to TailableCursor. Tailable means
cursor is not closed when the last data is retrieved. Rather, the cursor marks
the final object's position. You can resume using the cursor later, from
where it was located, if more data were received. Like any 'latent
cursor', the cursor may become invalid at some point (CursorNotFound)
for example if the final object it references were deleted.
=end item2
=begin item2
B<C-QF-SLAVEOK>: corresponds to SlaveOk.Allow query of replica slave.
Normally these return an error except for namespace 'local'.
=end item2
=begin item2
B<C-QF-OPLOGREPLAY>: corresponds to OplogReplay. Internal replication
use only - driver should not set.
=end item2
=begin item2
B<C-QF-NOCURSORTIMOUT>: corresponds to NoCursorTimeout. The server
normally times out idle cursors after an inactivity period (10 minutes) to
prevent excess memory use. Set this option to prevent that. When used, the
cursor must be removed explicitly using C<$cursor.kill()>.
=end item2
=begin item2
B<C-QF-AWAITDATA>: corresponds to AwaitData. Use with TailableCursor.
If we are at the end of the data, block for a while rather than returning no
data. After a timeout period, we do return as normal.
=end item2
=begin item2
B<C-QF-EXHAUST>: corresponds to Exhaust. Stream the data down full
blast in multiple 'more' packages, on the assumption that the client will fully
read all data queried. Faster when you are pulling a lot of data and know you
want to pull it all down. Note: the client is not allowed to not read all the
data unless it closes the connection.
=end item2
=begin item2
B<C-QF-PORTAIL>: corresponds to Partial. Get partial results from a
mongos if some shards are down (instead of throwing an error)
=end item2
=end pod
=finish
=comment =======================================================================
=begin comment
=head2 method find-one
Defined as
method find-one ( %criteria = { }, %projection = { } --> Hash ) {...}
Same as for find() except it will only return one document. It is as if
C<:number-to-return(1)> is set implicitly.
=head2 method find-and-modify
Defined as
method find-and-modify (
Hash $criteria = { }, Hash $projection = { },
Hash :$update = { }, Hash :$sort = { },
Bool :$remove = False, Bool :$new = False,
Bool :$upsert = False
--> Hash
) {
Search record by the given criteria and sort order.
=begin code
my @places = <amsterdam NY LA haarlem utrecht parijs oradour poitiers vienna>;
my %d1 = code => 'd1 ';
for ^5,(5...1) -> $code-postfix { # Insert a number of documents
%d1<code> ~= $code-postfix;
%d1<city> = @places.roll;
$collection.insert(%d1);
}
$doc = $collection.find-and-modify(
{code => 'd1 01234543'}, # Find this code
update => { '$set' => {code => 'd1 012'}}, # Change into 'd1 012'
:new # Return modified doc
);
=end code
=head2 method update
Defined as
method update (
Hash %selector, %update!, Bool :$upsert = False,
Bool :$multi-update = False
)
Update documents in the database. There are 2 flags defined.
=for item1
C<:upsert> If set, the database will insert the supplied object into the
collection if no matching document is found.
=for item1
C<:multi-update> If set, the database will update all matching objects in the
collection. Otherwise only updates first matching doc.
The commands used by MongoDB such as C<$set>, C<$inc> and C<$push> can easily
create unexpected errors in perl programs because scalars are written the same
way. Make sure you escape the $ sign or enclose the commands in single quoted
strings to prevent interpolation.
=begin code
# Update all documents
$collection.update({}, {'$set' => {company => 'Implix'}});
# Update documents for nick 'ph' or, when not existent, create a new document.
$collection.update( :upsert, {nick => 'pb'}, {'$push' => {versions => 7}});
=end code
=head2 method remove
Defined as
method remove ( %selector = {}, Bool :$single-remove = False )
Remove the selected documents from the database.
=for item2
C<:single-remove> If set, the database will remove only the first matching
document in the collection. Otherwise all matching documents will be removed.
=begin code
# Remove first document for nick 'ph'.
$collection.remove( :single-remove, {nick => 'pb'});
# Remove all documents
$collection.remove();
=end code
=head2 method drop
Defined as
method drop ( --> Hash )
Drop the current collection from the database.
This method will throw a X::MongoDB exception on failures.
=head2 method explain
Defined as
method explain ( %criteria = { } --> Hash )
Return information on the query plan using the criteria. There are many fields
in the document. The fields returned also depend on the type of queries. Look
for this information on the L<MongoDB site|http://docs.mongodb.org/manual/reference/method/cursor.explain>.
=head2 method count
Defined as
method count ( %criteria = { }, --> Int )
Count documents using search criteria without using find and a cursor..
=head2 method distinct
Defined as
method distinct ( $field-name!, %criteria = { }, --> Array )
Find distinct values of a field depending on criteria.
=head2 method group
Defined as
multi method group ( Str $js_reduce_func, Str :$key = '',
:%initial = {}, Str :$key_js_func = '',
:%condition = {}, Str :$finalize = ''
--> Hash )
multi method group ( BSON::Javascript $reduce-js-func, Str :$key = '',
:%initial = {}, BSON::Javascript :$key_js_func = '',
:%condition = {}, Str :$finalize = ''
--> Hash )
Groups documents in a collection by the specified keys and performs simple
aggregation functions. See also L<this
page|http://docs.mongodb.org/manual/reference/method/db.collection.group/>.
First method will call second with the javascript texts converted to
C<BSON::Javascript>.
The C<group> method does not work with sharded clusters. Use the
aggregation framework or map-reduce in sharded environments.
=head2 method map-reduce
Defined as
multi method map-reduce ( Str $map-js-func, Str $reduce-js-func, Hash :$out,
Str :$finalize, Hash :$criteria, Hash :$sort,
Hash :$scope, Int :$limit, Bool :$jsMode = False
--> Hash )
multi method map-reduce ( BSON::Javascript $map-js-func,
BSON::Javascript $reduce-js-func,
BSON::Javascript :$finalize,
Hash :$out, Hash :$criteria, Hash :$sort,
Hash :$scope, Int :$limit, Bool :$jsMode = False
--> Hash )
The C<map-reduce> method allows you to run map-reduce aggregation operations
over a collection. See also L<this
page|http://docs.mongodb.org/manual/reference/command/mapReduce/>.
First method will call second with the javascript texts converted to
C<BSON::Javascript>.
=head2 method ensure-index
Defined as
method ensure-index ( %key-spec!, %options = {} --> Nil )
Create a new index on the current collection. The %key-spec document specify
which indexes must be created and how. The %options is a document on how to
process the insertion. Depending on the type of index, %options can have
different keys.
See also information on the MongoDB site about L<general|http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/>,
L<text|http://docs.mongodb.org/manual/core/index-text/>, L<2dsphere|http://docs.mongodb.org/manual/core/2dsphere/>,
L<ed|http://docs.mongodb.org/manual/core/2d/> and L<geoHaystack|http://docs.mongodb.org/manual/core/geohaystack/>
indexes.
This method will throw a X::MongoDB exception on failures.
=head2 method drop-index
Defined as
method drop-index ( $key-spec! --> Hash )
Drop an index. The %key-spec specifies the keys to be dropped. It has the
same format as in ensure-index. When the %options<name> key is used when setting
an index, the name itself can be used to drop the index. Lastly, when the text
is '*', all indexes except for _id will be deleted. This is what drop-indexes()
will do for you.
=begin code
$collection.ensure-index( %( code1 => 1), %( name => 'testindex'));
$doc = $collection.drop-index('testindex');
=end code
This method will throw a X::MongoDB exception on failures.
=head2 method drop-indexes
Defined as
method drop-indexes ( --> Hash )
Drop all indexes for the collection except _id.
=head2 method get-indexes
method get-indexes ( --> MongoDB::Cursor )
Get a cursor with which to retrieve documents with index information in
the current collection. There is always one document of the _id_ index.
=head2 method stats
method stats ( Int :$scale = 1, Bool :$index-details = False,
Hash :$index-details-field,
Str :$index-details-name
--> Hash ) {...}
Get some statistics about indexes and other things.
=head2 method data-size
Defined as
method data-size ( --> Int )
Return size field of statistics. This is the total size of all records in a
collection. This value does not include the record header, which is 16 bytes per
record, but does include the record\u2019s padding. Additionally size does not
include the size of any indexes associated with the collection, which the
totalIndexSize field reports.
=head2 method insert
Defined as
method insert ( **@documents, Bool :$continue-on-error = False )
Insert a document. You may specify more than one. These documents must all be
hashes. Below are the possible ways to insert documents. Checks are made to see
if there are key names starting with a '$' or having a '.' in the name. Top
level keys are checked to see if C<_id> is used. When found, the collection
is checked for the value of the key to see it has been used before. The value
must be unique!
The flag C<:continue-on-error> can be set to let the insert continue its job
when a document insertion fails. This will not prevent checking of key names
mentioned above.
=begin code
my %d1 = k1 => 'v1', k2 => 'v2';
my Hash $d2 = {k1 => 'v1a', :k2<appia>, :k3('d1 d2')};
my @docs = $%( k2 => 'v2a', k5 => 'v5'), $%( k1 => 'v1b', k2 => 'v2b');
$collection.insert( :continue-on-error, %d1, $d2, |@docs);
=end code
}}
=end comment
=end pod