/
collection.js
1873 lines (1577 loc) · 60.2 KB
/
collection.js
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
// @file collection.js - DBCollection support in the mongo shell
// db.colName is a DBCollection object
// or db["colName"]
if ((typeof DBCollection) == "undefined") {
DBCollection = function(mongo, db, shortName, fullName) {
this._mongo = mongo;
this._db = db;
this._shortName = shortName;
this._fullName = fullName;
this.verify();
};
}
DBCollection.prototype.verify = function() {
assert(this._fullName, "no fullName");
assert(this._shortName, "no shortName");
assert(this._db, "no db");
assert.eq(this._fullName, this._db._name + "." + this._shortName, "name mismatch");
assert(this._mongo, "no mongo in DBCollection");
assert(this.getMongo(), "no mongo from getMongo()");
};
DBCollection.prototype.getName = function() {
return this._shortName;
};
DBCollection.prototype.help = function() {
var shortName = this.getName();
print("DBCollection help");
print("\tdb." + shortName + ".find().help() - show DBCursor help");
print(
"\tdb." + shortName +
".bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j");
print(
"\tdb." + shortName +
".count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS");
print(
"\tdb." + shortName +
".copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.");
print("\tdb." + shortName + ".convertToCapped(maxBytes) - calls {convertToCapped:'" +
shortName + "', size:maxBytes}} command");
print("\tdb." + shortName + ".createIndex(keypattern[,options])");
print("\tdb." + shortName + ".createIndexes([keypatterns], <options>)");
print("\tdb." + shortName + ".dataSize()");
print(
"\tdb." + shortName +
".deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j");
print(
"\tdb." + shortName +
".deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j");
print("\tdb." + shortName + ".distinct( key, query, <optional params> ) - e.g. db." +
shortName + ".distinct( 'x' ), optional parameters are: maxTimeMS");
print("\tdb." + shortName + ".drop() drop the collection");
print("\tdb." + shortName + ".dropIndex(index) - e.g. db." + shortName +
".dropIndex( \"indexName\" ) or db." + shortName + ".dropIndex( { \"indexKey\" : 1 } )");
print("\tdb." + shortName + ".dropIndexes()");
print("\tdb." + shortName +
".ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead");
print("\tdb." + shortName + ".explain().help() - show explain help");
print("\tdb." + shortName + ".reIndex()");
print(
"\tdb." + shortName +
".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.");
print("\t e.g. db." + shortName +
".find( {x:77} , {name:1, x:1} )");
print("\tdb." + shortName + ".find(...).count()");
print("\tdb." + shortName + ".find(...).limit(n)");
print("\tdb." + shortName + ".find(...).skip(n)");
print("\tdb." + shortName + ".find(...).sort(...)");
print("\tdb." + shortName + ".findOne([query], [fields], [options], [readConcern])");
print(
"\tdb." + shortName +
".findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS");
print(
"\tdb." + shortName +
".findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument");
print(
"\tdb." + shortName +
".findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument");
print("\tdb." + shortName + ".getDB() get DB object associated with collection");
print("\tdb." + shortName + ".getPlanCache() get query plan cache associated with collection");
print("\tdb." + shortName + ".getIndexes()");
print("\tdb." + shortName + ".group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )");
print("\tdb." + shortName + ".insert(obj)");
print(
"\tdb." + shortName +
".insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j");
print(
"\tdb." + shortName +
".insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j");
print("\tdb." + shortName + ".mapReduce( mapFunction , reduceFunction , <optional params> )");
print(
"\tdb." + shortName +
".aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor");
print("\tdb." + shortName + ".remove(query)");
print(
"\tdb." + shortName +
".replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j");
print("\tdb." + shortName +
".renameCollection( newName , <dropTarget> ) renames the collection.");
print(
"\tdb." + shortName +
".runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name");
print("\tdb." + shortName + ".save(obj)");
print("\tdb." + shortName + ".stats({scale: N, indexDetails: true/false, " +
"indexDetailsKey: <index key>, indexDetailsName: <index name>})");
// print("\tdb." + shortName + ".diskStorageStats({[extent: <num>,] [granularity: <bytes>,]
// ...}) - analyze record layout on disk");
// print("\tdb." + shortName + ".pagesInRAM({[extent: <num>,] [granularity: <bytes>,] ...}) -
// analyze resident memory pages");
print("\tdb." + shortName +
".storageSize() - includes free space allocated to this collection");
print("\tdb." + shortName + ".totalIndexSize() - size in bytes of all the indexes");
print("\tdb." + shortName + ".totalSize() - storage allocated for all data and indexes");
print(
"\tdb." + shortName +
".update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi");
print(
"\tdb." + shortName +
".updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j");
print(
"\tdb." + shortName +
".updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j");
print("\tdb." + shortName + ".validate( <full> ) - SLOW");
print("\tdb." + shortName + ".getShardVersion() - only for use with sharding");
print("\tdb." + shortName +
".getShardDistribution() - prints statistics about data distribution in the cluster");
print(
"\tdb." + shortName +
".getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function");
print(
"\tdb." + shortName +
".getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set");
print(
"\tdb." + shortName +
".setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection");
print(
"\tdb." + shortName +
".unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection");
print("\tdb." + shortName +
".latencyStats() - display operation latency histograms for this collection");
// print("\tdb." + shortName + ".getDiskStorageStats({...}) - prints a summary of disk usage
// statistics");
// print("\tdb." + shortName + ".getPagesInRAM({...}) - prints a summary of storage pages
// currently in physical memory");
return __magicNoPrint;
};
DBCollection.prototype.getFullName = function() {
return this._fullName;
};
DBCollection.prototype.getMongo = function() {
return this._db.getMongo();
};
DBCollection.prototype.getDB = function() {
return this._db;
};
DBCollection.prototype._makeCommand = function(cmd, params) {
var c = {};
c[cmd] = this.getName();
if (params)
Object.extend(c, params);
return c;
};
DBCollection.prototype._dbCommand = function(cmd, params) {
if (typeof(cmd) === "object")
return this._db._dbCommand(cmd, {}, this.getQueryOptions());
return this._db._dbCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions());
};
// Like _dbCommand, but applies $readPreference
DBCollection.prototype._dbReadCommand = function(cmd, params) {
if (typeof(cmd) === "object")
return this._db._dbReadCommand(cmd, {}, this.getQueryOptions());
return this._db._dbReadCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions());
};
DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand;
DBCollection.prototype.runReadCommand = DBCollection.prototype._dbReadCommand;
DBCollection.prototype._massageObject = function(q) {
if (!q)
return {};
var type = typeof q;
if (type == "function")
return {$where: q};
if (q.isObjectId)
return {_id: q};
if (type == "object")
return q;
if (type == "string") {
// If the string is 24 hex characters, it is most likely an ObjectId.
if (/^[0-9a-fA-F]{24}$/.test(q)) {
return {_id: ObjectId(q)};
}
return {$where: q};
}
throw Error("don't know how to massage : " + type);
};
DBCollection.prototype._validateObject = function(o) {
// Hidden property for testing purposes.
if (this.getMongo()._skipValidation)
return;
if (typeof(o) != "object")
throw Error("attempted to save a " + typeof(o) + " value. document expected.");
if (o._ensureSpecial && o._checkModify)
throw Error("can't save a DBQuery object");
};
DBCollection._allowedFields = {
$id: 1,
$ref: 1,
$db: 1
};
DBCollection.prototype._validateForStorage = function(o) {
// Hidden property for testing purposes.
if (this.getMongo()._skipValidation)
return;
this._validateObject(o);
for (var k in o) {
if (k.indexOf(".") >= 0) {
throw Error("can't have . in field names [" + k + "]");
}
if (k.indexOf("$") == 0 && !DBCollection._allowedFields[k]) {
throw Error("field names cannot start with $ [" + k + "]");
}
if (o[k] !== null && typeof(o[k]) === "object") {
this._validateForStorage(o[k]);
}
}
};
DBCollection.prototype.find = function(query, fields, limit, skip, batchSize, options) {
var cursor = new DBQuery(this._mongo,
this._db,
this,
this._fullName,
this._massageObject(query),
fields,
limit,
skip,
batchSize,
options || this.getQueryOptions());
{
const session = this.getDB().getSession();
const readPreference = session._serverSession.client.getReadPreference(session);
if (readPreference !== null) {
cursor.readPref(readPreference.mode, readPreference.tags);
}
const readConcern = session._serverSession.client.getReadConcern(session);
if (readConcern !== null) {
cursor.readConcern(readConcern.level);
}
}
return cursor;
};
DBCollection.prototype.findOne = function(query, fields, options, readConcern, collation) {
var cursor = this.find(query, fields, -1 /* limit */, 0 /* skip*/, 0 /* batchSize */, options);
if (readConcern) {
cursor = cursor.readConcern(readConcern);
}
if (collation) {
cursor = cursor.collation(collation);
}
if (!cursor.hasNext())
return null;
var ret = cursor.next();
if (cursor.hasNext())
throw Error("findOne has more than 1 result!");
if (ret.$err)
throw _getErrorWithCode(ret, "error " + tojson(ret));
return ret;
};
DBCollection.prototype.insert = function(obj, options, _allow_dot) {
if (!obj)
throw Error("no object passed to insert!");
var flags = 0;
var wc = undefined;
var allowDottedFields = false;
if (options === undefined) {
// do nothing
} else if (typeof(options) == 'object') {
if (options.ordered === undefined) {
// do nothing, like above
} else {
flags = options.ordered ? 0 : 1;
}
if (options.writeConcern)
wc = options.writeConcern;
if (options.allowdotted)
allowDottedFields = true;
} else {
flags = options;
}
// 1 = continueOnError, which is synonymous with unordered in the write commands/bulk-api
var ordered = ((flags & 1) == 0);
if (!wc)
wc = this.getWriteConcern();
var result = undefined;
var startTime =
(typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();
if (this.getMongo().writeMode() != "legacy") {
// Bit 1 of option flag is continueOnError. Bit 0 (stop on error) is the default.
var bulk = ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
var isMultiInsert = Array.isArray(obj);
if (isMultiInsert) {
obj.forEach(function(doc) {
bulk.insert(doc);
});
} else {
bulk.insert(obj);
}
try {
result = bulk.execute(wc);
if (!isMultiInsert)
result = result.toSingleResult();
} catch (ex) {
if (ex instanceof BulkWriteError) {
result = isMultiInsert ? ex.toResult() : ex.toSingleResult();
} else if (ex instanceof WriteCommandError) {
result = isMultiInsert ? ex : ex.toSingleResult();
} else {
// Other exceptions rethrown as-is.
throw ex;
}
}
} else {
if (!_allow_dot) {
this._validateForStorage(obj);
}
if (typeof(obj._id) == "undefined" && !Array.isArray(obj)) {
var tmp = obj; // don't want to modify input
obj = {_id: new ObjectId()};
for (var key in tmp) {
obj[key] = tmp[key];
}
}
this.getMongo().insert(this._fullName, obj, flags);
// enforce write concern, if required
if (wc)
result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
}
this._lastID = obj._id;
this._printExtraInfo("Inserted", startTime);
return result;
};
DBCollection.prototype._validateRemoveDoc = function(doc) {
// Hidden property for testing purposes.
if (this.getMongo()._skipValidation)
return;
for (var k in doc) {
if (k == "_id" && typeof(doc[k]) == "undefined") {
throw new Error("can't have _id set to undefined in a remove expression");
}
}
};
/**
* Does validation of the remove args. Throws if the parse is not successful, otherwise
* returns a document {query: <query>, justOne: <limit>, wc: <writeConcern>}.
*/
DBCollection.prototype._parseRemove = function(t, justOne) {
if (undefined === t)
throw Error("remove needs a query");
var query = this._massageObject(t);
var wc = undefined;
var collation = undefined;
if (typeof(justOne) === "object") {
var opts = justOne;
wc = opts.writeConcern;
justOne = opts.justOne;
collation = opts.collation;
}
// Normalize "justOne" to a bool.
justOne = justOne ? true : false;
// Handle write concern.
if (!wc) {
wc = this.getWriteConcern();
}
return {"query": query, "justOne": justOne, "wc": wc, "collation": collation};
};
DBCollection.prototype.remove = function(t, justOne) {
var parsed = this._parseRemove(t, justOne);
var query = parsed.query;
var justOne = parsed.justOne;
var wc = parsed.wc;
var collation = parsed.collation;
var result = undefined;
var startTime =
(typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();
if (this.getMongo().writeMode() != "legacy") {
var bulk = this.initializeOrderedBulkOp();
var removeOp = bulk.find(query);
if (collation) {
removeOp.collation(collation);
}
if (justOne) {
removeOp.removeOne();
} else {
removeOp.remove();
}
try {
result = bulk.execute(wc).toSingleResult();
} catch (ex) {
if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) {
result = ex.toSingleResult();
} else {
// Other exceptions thrown
throw Error(ex);
}
}
} else {
if (collation) {
throw new Error("collation requires use of write commands");
}
this._validateRemoveDoc(t);
this.getMongo().remove(this._fullName, query, justOne);
// enforce write concern, if required
if (wc)
result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
}
this._printExtraInfo("Removed", startTime);
return result;
};
DBCollection.prototype._validateUpdateDoc = function(doc) {
// Hidden property for testing purposes.
if (this.getMongo()._skipValidation)
return;
var firstKey = null;
for (var key in doc) {
firstKey = key;
break;
}
if (firstKey != null && firstKey[0] == '$') {
// for mods we only validate partially, for example keys may have dots
this._validateObject(doc);
} else {
// we're basically inserting a brand new object, do full validation
this._validateForStorage(doc);
}
};
/**
* Does validation of the update args. Throws if the parse is not successful, otherwise
* returns a document containing fields for query, obj, upsert, multi, wc, collation, and
* arrayFilters.
*
* Throws if the arguments are invalid.
*/
DBCollection.prototype._parseUpdate = function(query, obj, upsert, multi) {
if (!query)
throw Error("need a query");
if (!obj)
throw Error("need an object");
var wc = undefined;
var collation = undefined;
var arrayFilters = undefined;
// can pass options via object for improved readability
if (typeof(upsert) === "object") {
if (multi) {
throw Error("Fourth argument must be empty when specifying " +
"upsert and multi with an object.");
}
var opts = upsert;
multi = opts.multi;
wc = opts.writeConcern;
upsert = opts.upsert;
collation = opts.collation;
arrayFilters = opts.arrayFilters;
}
// Normalize 'upsert' and 'multi' to booleans.
upsert = upsert ? true : false;
multi = multi ? true : false;
if (!wc) {
wc = this.getWriteConcern();
}
return {
"query": query,
"obj": obj,
"upsert": upsert,
"multi": multi,
"wc": wc,
"collation": collation,
"arrayFilters": arrayFilters
};
};
DBCollection.prototype.update = function(query, obj, upsert, multi) {
var parsed = this._parseUpdate(query, obj, upsert, multi);
var query = parsed.query;
var obj = parsed.obj;
var upsert = parsed.upsert;
var multi = parsed.multi;
var wc = parsed.wc;
var collation = parsed.collation;
var arrayFilters = parsed.arrayFilters;
var result = undefined;
var startTime =
(typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();
if (this.getMongo().writeMode() != "legacy") {
var bulk = this.initializeOrderedBulkOp();
var updateOp = bulk.find(query);
if (upsert) {
updateOp = updateOp.upsert();
}
if (collation) {
updateOp.collation(collation);
}
if (arrayFilters) {
updateOp.arrayFilters(arrayFilters);
}
if (multi) {
updateOp.update(obj);
} else {
updateOp.updateOne(obj);
}
try {
result = bulk.execute(wc).toSingleResult();
} catch (ex) {
if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) {
result = ex.toSingleResult();
} else {
// Other exceptions thrown
throw Error(ex);
}
}
} else {
if (collation) {
throw new Error("collation requires use of write commands");
}
if (arrayFilters) {
throw new Error("arrayFilters requires use of write commands");
}
this._validateUpdateDoc(obj);
this.getMongo().update(this._fullName, query, obj, upsert, multi);
// Enforce write concern, if required
if (wc) {
result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
}
}
this._printExtraInfo("Updated", startTime);
return result;
};
DBCollection.prototype.save = function(obj, opts) {
if (obj == null)
throw Error("can't save a null");
if (typeof(obj) == "number" || typeof(obj) == "string")
throw Error("can't save a number or string");
if (typeof(obj._id) == "undefined") {
obj._id = new ObjectId();
return this.insert(obj, opts);
} else {
return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts));
}
};
DBCollection.prototype._genIndexName = function(keys) {
var name = "";
for (var k in keys) {
var v = keys[k];
if (typeof v == "function")
continue;
if (name.length > 0)
name += "_";
name += k + "_";
name += v;
}
return name;
};
DBCollection.prototype._indexSpec = function(keys, options) {
var ret = {ns: this._fullName, key: keys, name: this._genIndexName(keys)};
if (!options) {
} else if (typeof(options) == "string")
ret.name = options;
else if (typeof(options) == "boolean")
ret.unique = true;
else if (typeof(options) == "object") {
if (Array.isArray(options)) {
if (options.length > 3) {
throw new Error("Index options that are supplied in array form may only specify" +
" three values: name, unique, dropDups");
}
var nb = 0;
for (var i = 0; i < options.length; i++) {
if (typeof(options[i]) == "string")
ret.name = options[i];
else if (typeof(options[i]) == "boolean") {
if (options[i]) {
if (nb == 0)
ret.unique = true;
if (nb == 1)
ret.dropDups = true;
}
nb++;
}
}
} else {
Object.extend(ret, options);
}
} else {
throw Error("can't handle: " + typeof(options));
}
return ret;
};
DBCollection.prototype.createIndex = function(keys, options) {
return this.createIndexes([keys], options);
};
DBCollection.prototype.createIndexes = function(keys, options) {
if (!Array.isArray(keys)) {
throw new Error("createIndexes first argument should be an array");
}
var indexSpecs = Array(keys.length);
for (var i = 0; i < indexSpecs.length; i++) {
indexSpecs[i] = this._indexSpec(keys[i], options);
}
if (this.getMongo().writeMode() == "commands") {
for (var i = 0; i < indexSpecs.length; i++) {
delete (indexSpecs[i].ns); // ns is passed to the first element in the command.
}
return this._db.runCommand({createIndexes: this.getName(), indexes: indexSpecs});
} else if (this.getMongo().writeMode() == "compatibility") {
// Use the downconversion machinery of the bulk api to do a safe write, report response as a
// command response
var result = this._db.getCollection("system.indexes").insert(indexSpecs, 0, true);
if (result.hasWriteErrors() || result.hasWriteConcernError()) {
// Return the first error
var error = result.hasWriteErrors() ? result.getWriteErrors()[0]
: result.getWriteConcernError();
return {ok: 0.0, code: error.code, errmsg: error.errmsg};
} else {
return {ok: 1.0};
}
} else {
this._db.getCollection("system.indexes").insert(indexSpecs, 0, true);
}
};
DBCollection.prototype.ensureIndex = function(keys, options) {
var result = this.createIndex(keys, options);
if (this.getMongo().writeMode() != "legacy") {
return result;
}
err = this.getDB().getLastErrorObj();
if (err.err) {
return err;
}
// nothing returned on success
};
DBCollection.prototype.reIndex = function() {
return this._db.runCommand({reIndex: this.getName()});
};
DBCollection.prototype.dropIndexes = function() {
if (arguments.length)
throw Error("dropIndexes doesn't take arguments");
var res = this._db.runCommand({deleteIndexes: this.getName(), index: "*"});
assert(res, "no result from dropIndex result");
if (res.ok)
return res;
if (res.errmsg.match(/not found/))
return res;
throw _getErrorWithCode(res, "error dropping indexes : " + tojson(res));
};
DBCollection.prototype.drop = function() {
if (arguments.length > 0)
throw Error("drop takes no argument");
var ret = this._db.runCommand({drop: this.getName()});
if (!ret.ok) {
if (ret.errmsg == "ns not found")
return false;
throw _getErrorWithCode(ret, "drop failed: " + tojson(ret));
}
return true;
};
DBCollection.prototype.findAndModify = function(args) {
var cmd = {findandmodify: this.getName()};
for (var key in args) {
cmd[key] = args[key];
}
{
const kWireVersionSupportingRetryableWrites = 6;
const serverSupportsRetryableWrites =
this.getMongo().getMinWireVersion() <= kWireVersionSupportingRetryableWrites &&
kWireVersionSupportingRetryableWrites <= this.getMongo().getMaxWireVersion();
const session = this.getDB().getSession();
if (serverSupportsRetryableWrites && session.getOptions().shouldRetryWrites() &&
session._serverSession.canRetryWrites(cmd)) {
cmd = session._serverSession.assignTransactionNumber(cmd);
}
}
var ret = this._db.runCommand(cmd);
if (!ret.ok) {
if (ret.errmsg == "No matching object found") {
return null;
}
throw _getErrorWithCode(ret, "findAndModifyFailed failed: " + tojson(ret));
}
return ret.value;
};
DBCollection.prototype.renameCollection = function(newName, dropTarget) {
if (arguments.length === 1 && typeof newName === 'object') {
if (newName.hasOwnProperty('dropTarget')) {
dropTarget = newName['dropTarget'];
}
newName = newName['to'];
}
if (typeof dropTarget === 'undefined') {
dropTarget = false;
}
if (typeof newName !== 'string' || typeof dropTarget !== 'boolean') {
throw Error(
'renameCollection must either take a string and an optional boolean or an object.');
}
return this._db._adminCommand({
renameCollection: this._fullName,
to: this._db._name + "." + newName,
dropTarget: dropTarget
});
};
// Display verbose information about the operation
DBCollection.prototype._printExtraInfo = function(action, startTime) {
if (typeof _verboseShell === 'undefined' || !_verboseShell) {
__callLastError = true;
return;
}
// explicit w:1 so that replset getLastErrorDefaults aren't used here which would be bad.
var res = this._db.getLastErrorCmd(1);
if (res) {
if (res.err != undefined && res.err != null) {
// error occurred, display it
print(res.err);
return;
}
var info = action + " ";
// hack for inserted because res.n is 0
info += action != "Inserted" ? res.n : 1;
if (res.n > 0 && res.updatedExisting != undefined)
info += " " + (res.updatedExisting ? "existing" : "new");
info += " record(s)";
var time = new Date().getTime() - startTime;
info += " in " + time + "ms";
print(info);
}
};
DBCollection.prototype.validate = function(full) {
var cmd = {validate: this.getName()};
if (typeof(full) == 'object') // support arbitrary options here
Object.extend(cmd, full);
else
cmd.full = full;
var res = this._db.runCommand(cmd);
if (typeof(res.valid) == 'undefined') {
// old-style format just put everything in a string. Now using proper fields
res.valid = false;
var raw = res.result || res.raw;
if (raw) {
var str = "-" + tojson(raw);
res.valid = !(str.match(/exception/) || str.match(/corrupt/));
var p = /lastExtentSize:(\d+)/;
var r = p.exec(str);
if (r) {
res.lastExtentSize = Number(r[1]);
}
}
}
return res;
};
/**
* Invokes the storageDetails command to provide aggregate and (if requested) detailed information
* regarding the layout of records and deleted records in the collection extents.
* getDiskStorageStats provides a human-readable summary of the command output
*/
DBCollection.prototype.diskStorageStats = function(opt) {
var cmd = {storageDetails: this.getName(), analyze: 'diskStorage'};
if (typeof(opt) == 'object')
Object.extend(cmd, opt);
var res = this._db.runCommand(cmd);
if (!res.ok && res.errmsg.match(/no such cmd/)) {
print("this command requires starting mongod with --enableExperimentalStorageDetailsCmd");
}
return res;
};
// Refer to diskStorageStats
DBCollection.prototype.getDiskStorageStats = function(params) {
var stats = this.diskStorageStats(params);
if (!stats.ok) {
print("error executing storageDetails command: " + stats.errmsg);
return;
}
print("\n " + "size".pad(9) + " " + "# recs".pad(10) + " " +
"[===occupied by BSON=== ---occupied by padding--- free ]" + " " +
"bson".pad(8) + " " + "rec".pad(8) + " " + "padding".pad(8));
print();
var BAR_WIDTH = 70;
var formatSliceData = function(data) {
var bar = _barFormat(
[
[data.bsonBytes / data.onDiskBytes, "="],
[(data.recBytes - data.bsonBytes) / data.onDiskBytes, "-"]
],
BAR_WIDTH);
return sh._dataFormat(data.onDiskBytes).pad(9) + " " + data.numEntries.toFixed(0).pad(10) +
" " + bar + " " + (data.bsonBytes / data.onDiskBytes).toPercentStr().pad(8) + " " +
(data.recBytes / data.onDiskBytes).toPercentStr().pad(8) + " " +
(data.recBytes / data.bsonBytes).toFixed(4).pad(8);
};
var printExtent = function(ex, rng) {
print("--- extent " + rng + " ---");
print("tot " + formatSliceData(ex));
print();
if (ex.slices) {
for (var c = 0; c < ex.slices.length; c++) {
var slice = ex.slices[c];
print(("" + c).pad(3) + " " + formatSliceData(slice));
}
print();
}
};
if (stats.extents) {
print("--- extent overview ---\n");
for (var i = 0; i < stats.extents.length; i++) {
var ex = stats.extents[i];
print(("" + i).pad(3) + " " + formatSliceData(ex));
}
print();
if (params && (params.granularity || params.numberOfSlices)) {
for (var i = 0; i < stats.extents.length; i++) {
printExtent(stats.extents[i], i);
}
}
} else {
printExtent(stats, "range " + stats.range);
}
};
/**
* Invokes the storageDetails command to report the percentage of virtual memory pages of the
* collection storage currently in physical memory (RAM).
* getPagesInRAM provides a human-readable summary of the command output
*/
DBCollection.prototype.pagesInRAM = function(opt) {
var cmd = {storageDetails: this.getName(), analyze: 'pagesInRAM'};
if (typeof(opt) == 'object')
Object.extend(cmd, opt);
var res = this._db.runCommand(cmd);
if (!res.ok && res.errmsg.match(/no such cmd/)) {
print("this command requires starting mongod with --enableExperimentalStorageDetailsCmd");
}
return res;
};
// Refer to pagesInRAM
DBCollection.prototype.getPagesInRAM = function(params) {
var stats = this.pagesInRAM(params);
if (!stats.ok) {
print("error executing storageDetails command: " + stats.errmsg);
return;
}
var BAR_WIDTH = 70;
var formatExtentData = function(data) {
return "size".pad(8) + " " + _barFormat([[data.inMem, '=']], BAR_WIDTH) + " " +
data.inMem.toPercentStr().pad(7);
};
var printExtent = function(ex, rng) {
print("--- extent " + rng + " ---");
print("tot " + formatExtentData(ex));
print();
if (ex.slices) {
print("\tslices, percentage of pages in memory (< .1% : ' ', <25% : '.', " +