-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathdb.js
More file actions
1847 lines (1572 loc) · 59.5 KB
/
db.js
File metadata and controls
1847 lines (1572 loc) · 59.5 KB
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
// db.js
let _defaultWriteConcern = {w: "majority", wtimeout: 10 * 60 * 1000};
const kWireVersionSupportingScramSha256Fallback = 15;
const DB =
globalThis.DB ??
function (mongo, name) {
this._mongo = mongo;
this._name = name;
};
/**
* Rotate certificates, CRLs, and CA files.
* @param {String} message optional message for server to log at rotation time
*/
DB.prototype.rotateCertificates = function (message) {
return this._adminCommand({rotateCertificates: 1, message});
};
/**
* @this {DB}
*/
DB.prototype.getMongo = function () {
assert(this._mongo, "why no mongo!");
return this._mongo;
};
/**
* @this {DB}
*/
DB.prototype.getSiblingDB = function (name) {
return this.getSession().getDatabase(name);
};
DB.prototype.getSisterDB = DB.prototype.getSiblingDB;
/**
* @this {DB}
*/
DB.prototype.getName = function () {
return this._name;
};
/**
* Gets DB level statistics. opt can be a number representing the scale for backwards compatibility
* or a document with options passed along to the dbstats command.
* @this {DB}
*/
DB.prototype.stats = function (opt) {
let cmd = {dbstats: 1};
if (opt === undefined) return this.runCommand(cmd);
if (typeof opt !== "object") return this.runCommand(Object.extend(cmd, {scale: opt}));
return this.runCommand(Object.extend(cmd, opt));
};
/**
* @this {DB}
*/
DB.prototype.getCollection = function (name) {
return new DBCollection(this._mongo, this, name, this._name + "." + name);
};
DB.prototype.commandHelp = function (name) {
let c = {};
c[name] = 1;
c.help = true;
let res = this.runCommand(c);
if (!res.ok) throw _getErrorWithCode(res, res.errmsg);
return res.help;
};
const kAggStagesThatNotSupportSecondaryReadPreference = new Set([
// Can't set a secondary read preference on $listClusterCatalog collection because it
// only accepts 'local' read concern.
"$listClusterCatalog",
]);
// Utility to attach readPreference if needed.
DB.prototype._attachReadPreferenceToCommand = function (cmdObj, readPref) {
"use strict";
// If the user has not set a read pref, return the original 'cmdObj'.
if (readPref === null || typeof readPref !== "object") {
return cmdObj;
}
// If user specifies $readPreference manually, then don't change it.
if (cmdObj.hasOwnProperty("$readPreference")) {
return cmdObj;
}
const cmdName = Object.keys(cmdObj)[0];
// Prevent setting `secondary` read preference if it's not allowed on specific aggregate stages.
if (
cmdName === "aggregate" &&
readPref?.mode === "secondary" &&
cmdObj.pipeline &&
Array.isArray(cmdObj.pipeline) &&
cmdObj.pipeline.length !== 0
) {
const stages = cmdObj.pipeline.map((obj) => (obj instanceof Object ? Object.keys(obj)[0] : ""));
if (stages.some((stage) => kAggStagesThatNotSupportSecondaryReadPreference.has(stage))) {
return cmdObj;
}
}
// Copy object so we don't mutate the original.
let clonedCmdObj = Object.extend({}, cmdObj);
clonedCmdObj["$readPreference"] = readPref;
return clonedCmdObj;
};
/**
* If someone passes i.e. runCommand("foo", {bar: "baz"}), we merge it in to
* runCommand({foo: 1, bar: "baz"}).
* If we already have a command object in the first argument, we ensure that the second
* argument 'extraKeys' is either null or an empty object. This prevents users from accidentally
* calling runCommand({foo: 1}, {bar: 1}) and expecting the final command invocation to be
* runCommand({foo: 1, bar: 1}).
* This helper abstracts that logic.
*/
DB.prototype._mergeCommandOptions = function (obj, extraKeys) {
"use strict";
if (typeof obj === "object") {
if (Object.keys(extraKeys || {}).length > 0) {
throw Error(
"Unexpected second argument to DB.runCommand(): (type: " + typeof extraKeys + "): " + tojson(extraKeys),
);
}
return obj;
} else if (typeof obj !== "string") {
throw Error(
"First argument to DB.runCommand() must be either an object or a string: " +
"(type: " +
typeof obj +
"): " +
tojson(obj),
);
}
let commandName = obj;
let mergedCmdObj = {};
mergedCmdObj[commandName] = 1;
if (!extraKeys) {
return mergedCmdObj;
} else if (typeof extraKeys === "object") {
// this will traverse the prototype chain of extra, but keeping
// to maintain legacy behavior
for (let key in extraKeys) {
mergedCmdObj[key] = extraKeys[key];
}
} else {
throw Error(
"Second argument to DB.runCommand(" +
commandName +
") must be an object: (type: " +
typeof extraKeys +
"): " +
tojson(extraKeys),
);
}
return mergedCmdObj;
};
// Like runCommand but applies readPreference if one has been set
// on the connection. Also sets slaveOk if a (non-primary) readPref has been set.
/**
* Run a read command with appropriate read preference.
* @this {DB}
*/
DB.prototype.runReadCommand = function (obj, extra, queryOptions) {
"use strict";
// Support users who call this function with a string commandName, e.g.
// db.runReadCommand("commandName", {arg1: "value", arg2: "value"}).
obj = this._mergeCommandOptions(obj, extra);
queryOptions = queryOptions !== undefined ? queryOptions : this.getQueryOptions();
{
const session = this.getSession();
const readPreference = session._getSessionAwareClient().getReadPreference(session);
if (readPreference !== null) {
obj = this._attachReadPreferenceToCommand(obj, readPreference);
if (readPreference.mode !== "primary") {
// Set slaveOk if readPrefMode has been explicitly set with a readPreference
// other than primary.
queryOptions |= 4;
}
}
}
// The 'extra' parameter is not used as we have already created a merged command object.
return this.runCommand(obj, null, queryOptions);
};
/**
* Run command implementation. Used internally by runCommand.
* @this {DB}
*/
DB.prototype._runCommandImpl = function (name, obj, options) {
const session = this.getSession();
const result = session._getSessionAwareClient().runCommand(session, name, obj, options);
// Set change stream version into the result object for easier assertions.
if (obj.pipeline && obj.pipeline.length > 0 && obj.pipeline[0].$changeStream) {
// TODO: SERVER-52253 Enable feature flag for Improved change stream handling of cluster topology changes.
const changeStreamVersion = obj.pipeline[0].$changeStream.version ?? "v1";
result._changeStreamVersion = changeStreamVersion;
}
return result;
};
/**
* Run a database command.
* @this {DB}
*/
DB.prototype.runCommand = function (obj, extra, queryOptions) {
"use strict";
// Support users who call this function with a string commandName, e.g.
// db.runCommand("commandName", {arg1: "value", arg2: "value"}).
let mergedObj = this._mergeCommandOptions(obj, extra);
// if options were passed (i.e. because they were overridden on a collection), use them.
// Otherwise use getQueryOptions.
let options = typeof queryOptions !== "undefined" ? queryOptions : this.getQueryOptions();
try {
return this._runCommandImpl(this._name, mergedObj, options);
} catch (ex) {
// When runCommand flowed through query, a connection error resulted in the message
// "error doing query: failed". Even though this message is arguably incorrect
// for a command failing due to a connection failure, we preserve it for backwards
// compatibility. See SERVER-18334 for details.
if (ex.hasOwnProperty("message") && ex.message.indexOf("network error") >= 0) {
throw new Error("error doing query: failed: " + ex.message);
}
throw ex;
}
};
DB.prototype._dbCommand = DB.prototype.runCommand;
DB.prototype._dbReadCommand = DB.prototype.runReadCommand;
/**
* Run a command on the admin database.
* @this {DB}
*/
DB.prototype.adminCommand = function (obj, extra) {
if (this._name == "admin") return this.runCommand(obj, extra);
return this.getSiblingDB("admin").runCommand(obj, extra);
};
DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name
DB.prototype._helloOrLegacyHello = function (args) {
let cmd = this.getMongo().getApiParameters().version ? {hello: 1} : {isMaster: 1};
if (args) {
Object.assign(cmd, args);
}
return this.runCommand(cmd);
};
DB.prototype._runCommandWithoutApiStrict = function (command) {
let commandWithoutApiStrict = {...command};
if (this.getMongo().getApiParameters().strict) {
// Permit this command invocation, even if it's not in the requested API version.
commandWithoutApiStrict["apiStrict"] = false;
}
return this.runCommand(commandWithoutApiStrict);
};
DB.prototype._runAggregate = function (cmdObj, aggregateOptions) {
assert(cmdObj.pipeline instanceof Array, "cmdObj must contain a 'pipeline' array");
assert(cmdObj.aggregate !== undefined, "cmdObj must contain 'aggregate' field");
assert(
aggregateOptions === undefined || aggregateOptions instanceof Object,
"'aggregateOptions' argument must be an object",
);
// Disallow explicit API parameters on the aggregate shell helper; callers should use runCommand
// directly if they want to test this.
assert.noAPIParams(aggregateOptions);
// Make a copy of the initial command object, i.e. {aggregate: x, pipeline: [...]}.
cmdObj = Object.extend({}, cmdObj);
// Make a copy of the aggregation options.
let optcpy = Object.extend({}, aggregateOptions || {});
if ("batchSize" in optcpy) {
if (optcpy.cursor == null) {
optcpy.cursor = {};
}
optcpy.cursor.batchSize = optcpy["batchSize"];
delete optcpy["batchSize"];
} else if ("useCursor" in optcpy) {
if (optcpy.cursor == null) {
optcpy.cursor = {};
}
delete optcpy["useCursor"];
}
const maxAwaitTimeMS = optcpy.maxAwaitTimeMS;
delete optcpy.maxAwaitTimeMS;
// Reassign the cleaned-up options.
aggregateOptions = optcpy;
// Add the options to the command object.
Object.extend(cmdObj, aggregateOptions);
if (!("cursor" in cmdObj)) {
cmdObj.cursor = {};
}
const res = this.runReadCommand(cmdObj);
assert.commandWorked(res, "aggregate failed");
if ("cursor" in res) {
let batchSizeValue = undefined;
if (cmdObj["cursor"]["batchSize"] > 0) {
batchSizeValue = cmdObj["cursor"]["batchSize"];
}
return new DBCommandCursor(this, res, batchSizeValue, maxAwaitTimeMS);
}
return res;
};
DB.prototype.aggregate = function (pipeline, aggregateOptions) {
assert(pipeline instanceof Array, "pipeline argument must be an array");
const cmdObj = this._mergeCommandOptions("aggregate", {pipeline});
return this._runAggregate(cmdObj, aggregateOptions || {});
};
/**
Create a new collection in the database. Normally, collection creation is automatic. You
would
use this function if you wish to specify special options on creation.
If the collection already exists, no action occurs.
<p>Options:</p>
<ul>
<li>
size: desired initial extent size for the collection. Must be <= 1000000000.
for fixed size (capped) collections, this size is the total/max size of the
collection.
</li>
<li>
capped: if true, this is a capped collection (where old data rolls out).
</li>
<li> max: maximum number of objects if capped (optional).</li>
<li>
storageEngine: BSON document containing storage engine specific options. Format:
{
storageEngine: {
storageEngine1: {
...
},
storageEngine2: {
...
},
...
}
}
</li>
</ul>
<p>Example:</p>
<code>db.createCollection("movies", { size: 10 * 1024 * 1024, capped:true } );</code>
* @param {String} name Name of new collection to create
* @param {Object} options Object with options for call. Options are listed above.
* @return {Object} returned has member ok set to true if operation succeeds, false otherwise.
*/
DB.prototype.createCollection = function (name, opt) {
let options = opt || {};
let cmd = {create: name};
Object.extend(cmd, options);
return this._dbCommand(cmd);
};
/**
* Command to create a view based on the specified aggregation pipeline.
* Usage: db.createView(name, viewOn, pipeline: [{ $operator: {...}}, ... ])
*
* @param name String - name of the new view to create
* @param viewOn String - name of the backing view or collection
* @param pipeline [{ $operator: {...}}, ... ] - the aggregation pipeline that defines the view
* @param options { } - options on the view, e.g., collations
*/
DB.prototype.createView = function (name, viewOn, pipeline, opt) {
let options = opt || {};
let cmd = {create: name};
if (viewOn == undefined) {
throw Error("Must specify a backing view or collection");
}
// Since we allow a single stage pipeline to be specified as an object
// in aggregation, we need to account for that here for consistency.
if (pipeline != undefined) {
if (!Array.isArray(pipeline)) {
pipeline = [pipeline];
}
}
options.pipeline = pipeline;
options.viewOn = viewOn;
Object.extend(cmd, options);
return this._dbCommand(cmd);
};
/**
* @deprecated use getProfilingStatus
* Returns the current profiling level of this database
* @return SOMETHING_FIXME or null on error
*/
DB.prototype.getProfilingLevel = function () {
let res = assert.commandWorked(this._dbCommand({profile: -1}));
return res ? res.was : null;
};
/**
* @return the current profiling status
* example { was : 0, slowms : 100 }
* @return SOMETHING_FIXME or null on error
*/
DB.prototype.getProfilingStatus = function () {
let res = this._dbCommand({profile: -1});
if (!res.ok) throw _getErrorWithCode(res, "profile command failed: " + tojson(res));
delete res.ok;
return res;
};
/**
* Erase the entire database.
* @params writeConcern: (document) expresses the write concern of the drop command.
* @return Object returned has member ok set to true if operation succeeds, false otherwise.
*/
DB.prototype.dropDatabase = function (writeConcern) {
return this._dbCommand({dropDatabase: 1, writeConcern: writeConcern ? writeConcern : _defaultWriteConcern});
};
/**
* Shuts down the database. Must be run while using the admin database.
* @param opts Options for shutdown. Possible options are:
* - force: (boolean) if the server should shut down, even if there is no
* up-to-date secondary
* - timeoutSecs: (number) the server will continue checking over timeoutSecs
* if any other servers have caught up enough for it to shut down.
*/
DB.prototype.shutdownServer = function (opts) {
if ("admin" != this._name) {
return "shutdown command only works with the admin database; try 'use admin'";
}
let cmd = {"shutdown": 1};
opts ||= {};
for (let o in opts) {
cmd[o] = opts[o];
}
try {
let res = this.runCommand(cmd);
if (!res.ok) {
throw _getErrorWithCode(res, "shutdownServer failed: " + tojson(res));
}
throw Error("shutdownServer failed: server is still up.");
} catch (e) {
// we expect the command to not return a response, as the server will shut down
// immediately.
if (isNetworkError(e)) {
print("server should be down...");
return;
}
throw e;
}
};
DB.prototype.help = function () {
print("DB methods:");
print(
"\tdb.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]",
);
print(
"\tdb.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor",
);
print("\tdb.auth(username, password)");
print("\tdb.commandHelp(name) returns the help for the command");
print("\tdb.createUser(userDocument)");
print("\tdb.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})");
print("\tdb.currentOp() displays currently executing operations in the db");
print("\tdb.dropDatabase(writeConcern)");
print("\tdb.dropUser(username)");
print("\tdb.eval() - deprecated");
print("\tdb.fsyncLock() flush data to disk and lock server for backups");
print("\tdb.fsyncUnlock() unlocks server following a db.fsyncLock()");
print("\tdb.checkMetadataConsistency() checks the consistency of the metadata in the db");
print("\tdb.getCollection(cname) same as db['cname'] or db.cname");
print(
"\tdb.getCollectionInfos([filter]) - returns a list that contains the names and options" +
" of the db's collections",
);
print("\tdb.getCollectionNames()");
print("\tdb.getLogComponents()");
print("\tdb.getMongo() get the server connection object");
print("\tdb.getMongo().setSecondaryOk() allow queries on a replication secondary server");
print("\tdb.getName()");
print("\tdb.getProfilingLevel() - deprecated");
print("\tdb.getProfilingStatus() - returns if profiling is on and slow threshold");
print("\tdb.getReplicationInfo()");
print("\tdb.getSiblingDB(name) get the db at the same server as this one");
print(
"\tdb.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set",
);
print("\tdb.hostInfo() get details about the server's host");
print("\tdb.isMaster() check replica primary status");
print("\tdb.hello() check replica primary status");
print("\tdb.killOp(opid) kills the current operation in the db");
print("\tdb.listCommands() lists all the db commands");
print("\tdb.loadServerScripts() loads all the scripts in db.system.js");
print("\tdb.logout()");
print("\tdb.printCollectionStats()");
print("\tdb.printReplicationInfo()");
print("\tdb.printShardingStatus()");
print("\tdb.printSecondaryReplicationInfo()");
print("\tdb.rotateCertificates(message) - rotates certificates, CRLs, and CA files and logs an optional message");
print("\tdb.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}");
print("\tdb.serverStatus()");
print("\tdb.setLogLevel(level,<component>)");
print("\tdb.setProfilingLevel(level,slowms) 0=off 1=slow 2=all");
print("\tdb.setVerboseShell(flag) display extra information in shell output");
print("\tdb.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db");
print("\tdb.shutdownServer()");
print("\tdb.stats()");
print("\tdb.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db");
print("\tdb.version() current version of the server");
print(
"\tdb.watch() - opens a change stream cursor for a database to report on all " +
" changes to its non-system collections.",
);
return __magicNoPrint;
};
DB.prototype.printCollectionStats = function (scale) {
if (arguments.length > 1) {
print("printCollectionStats() has a single optional argument (scale)");
return;
}
if (typeof scale != "undefined") {
if (typeof scale != "number") {
print("scale has to be a number >= 1");
return;
}
if (scale < 1) {
print("scale has to be >= 1");
return;
}
}
let mydb = this;
this.getCollectionNames().forEach(function (z) {
print(z);
printjson(mydb.getCollection(z).stats(scale));
print("---");
});
};
/**
* Configures settings for capturing operations inside the system.profile collection and in the
* slow query log.
*
* The 'level' can be 0, 1, or 2:
* - 0 means that profiling is off and nothing will be written to system.profile.
* - 1 means that profiling is on for operations slower than the currently configured 'slowms'
* threshold (more on 'slowms' below).
* - 2 means that profiling is on for all operations, regardless of whether or not they are
* slower than 'slowms'.
*
* The 'options' parameter, if a number, is interpreted as the 'slowms' value to send to the
* server. 'slowms' determines the threshold, in milliseconds, above which slow operations get
* profiled at profiling level 1 or logged at logLevel 0.
*
* If 'options' is not a number, it is expected to be an object containing additional parameters
* to get passed to the server. For example, db.setProfilingLevel(2, {foo: "bar"}) will issue
* the command {profile: 2, foo: "bar"} to the server.
*/
DB.prototype.setProfilingLevel = function (level, options) {
if (level < 0 || level > 2) {
let errorText = "input level " + level + " is out of range [0..2]";
let errorObject = new Error(errorText);
errorObject["dbSetProfilingException"] = errorText;
throw errorObject;
}
let cmd = {profile: level};
if (isNumber(options)) {
cmd.slowms = options;
} else {
cmd = Object.extend(cmd, options);
}
return assert.commandWorked(this._dbCommand(cmd));
};
/**
* @deprecated
* <p> Evaluate a js expression at the database server.</p>
*
* <p>Useful if you need to touch a lot of data lightly; in such a scenario
* the network transfer of the data could be a bottleneck. A good example
* is "select count(*)" -- can be done server side via this mechanism.
* </p>
*
* <p>
* If the eval fails, an exception is thrown of the form:
* </p>
* <code>{ dbEvalException: { retval: functionReturnValue, ok: num [, errno: num] [, errmsg:
*str] } }</code>
*
* <p>Example: </p>
* <code>print( "mycount: " + db.eval( function(){db.mycoll.find({},{_id:ObjId()}).length();}
*);</code>
*
* @param {Function} jsfunction Javascript function to run on server. Note this it not a
*closure, but rather just "code".
* @return result of your function, or null if error
*
*/
DB.prototype.eval = function (jsfunction, ...args) {
print("WARNING: db.eval is deprecated");
let cmd = {$eval: jsfunction};
if (args.length > 0) {
cmd.args = args;
}
let res = this._dbCommand(cmd);
if (!res.ok) throw _getErrorWithCode(res, tojson(res));
return res.retval;
};
DB.prototype.dbEval = DB.prototype.eval;
/**
* <p>
* An array of grouped items is returned. The array must fit in RAM, thus this function is not
* suitable when the return set is extremely large.
* </p>
* <p>
* To order the grouped data, simply sort it client side upon return.
* <p>
Defaults
cond may be null if you want to run against all rows in the collection
keyf is a function which takes an object and returns the desired key. set either key or
keyf (not both).
* </p>
*/
DB.prototype.groupeval = function (parmsObj) {
let groupFunction = function () {
var parms = args[0]; // eslint-disable-line
let c = globalThis.db[parms.ns].find(parms.cond || {});
let map = new BSONAwareMap();
let pks = parms.key ? Object.keySet(parms.key) : null;
let pkl = pks ? pks.length : 0;
let key = {};
while (c.hasNext()) {
let obj = c.next();
if (pks) {
for (let i = 0; i < pkl; i++) {
let k = pks[i];
key[k] = obj[k];
}
} else {
key = parms.$keyf(obj);
}
let aggObj = map.get(key);
if (aggObj == null) {
let newObj = Object.extend({}, key); // clone
aggObj = Object.extend(newObj, parms.initial);
map.put(key, aggObj);
}
parms.$reduce(obj, aggObj);
}
return map.values();
};
return this.eval(groupFunction, this._groupFixParms(parmsObj));
};
DB.prototype._groupFixParms = function (parmsObj) {
let parms = Object.extend({}, parmsObj);
if (parms.reduce) {
parms.$reduce = parms.reduce; // must have $ to pass to db
delete parms.reduce;
}
if (parms.keyf) {
parms.$keyf = parms.keyf;
delete parms.keyf;
}
return parms;
};
DB.prototype.forceError = function () {
return this.runCommand({forceerror: 1});
};
DB.prototype._getCollectionInfosCommand = function (
filter,
nameOnly = false,
authorizedCollections = false,
options = {},
) {
filter ||= {};
const cmd = {
listCollections: 1,
filter,
nameOnly,
authorizedCollections,
};
const res = this.runCommand(Object.merge(cmd, options));
if (!res.ok) {
throw _getErrorWithCode(res, "listCollections failed: " + tojson(res));
}
return new DBCommandCursor(this, res).toArray().sort(compareOn("name"));
};
DB.prototype._getCollectionInfosFromPrivileges = function () {
let ret = this.runCommand({connectionStatus: 1, showPrivileges: 1});
if (!ret.ok) {
throw _getErrorWithCode(ret, "Failed to acquire collection information from privileges");
}
// Parse apart collection information.
let result = [];
let privileges = ret.authInfo.authenticatedUserPrivileges;
if (privileges === undefined) {
return result;
}
privileges.forEach((privilege) => {
let resource = privilege.resource;
if (resource === undefined) {
return;
}
let db = resource.db;
if (db === undefined || db !== this.getName()) {
return;
}
let collection = resource.collection;
if (collection === undefined || typeof collection !== "string" || collection === "") {
return;
}
result.push({name: collection});
});
return result.sort(compareOn("name"));
};
/**
* Returns a list that contains the names and options of this database's collections, sorted
* by collection name. An optional filter can be specified to match only collections with
* certain metadata.
*/
DB.prototype.getCollectionInfos = function (filter, nameOnly = false, authorizedCollections = false) {
try {
return this._getCollectionInfosCommand(filter, nameOnly, authorizedCollections);
} catch (ex) {
if (ex.code !== ErrorCodes.Unauthorized) {
// We cannot recover from this error, propagate it.
throw ex;
}
// We may be able to compute a set of *some* collections which exist and we have access
// to from our privileges. For this to work, the previous operation must have failed due
// to authorization, we must be attempting to recover the names of our own collections,
// and no filter can have been provided.
if (
nameOnly &&
authorizedCollections &&
Object.getOwnPropertyNames(filter).length === 0 &&
ex.code === ErrorCodes.Unauthorized
) {
print(
"Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus",
);
return this._getCollectionInfosFromPrivileges();
}
throw ex;
}
};
DB.prototype._getCollectionNamesInternal = function (options) {
return this._getCollectionInfosCommand({}, true, true, options).map(function (infoObj) {
return infoObj.name;
});
};
/**
* Returns this database's list of collection names in sorted order.
*/
DB.prototype.getCollectionNames = function () {
return this._getCollectionNamesInternal({});
};
DB.prototype.tojson = function () {
return this._name;
};
DB.prototype.toString = function () {
return this._name;
};
DB.prototype.isMaster = function () {
return this.runCommand("isMaster");
};
DB.prototype.hello = function () {
return this.runCommand("hello");
};
DB.prototype.currentOp = function (arg) {
try {
const results = this.currentOpCursor(arg).toArray();
let res = {"inprog": results.length > 0 ? results : [], "ok": 1};
Object.defineProperty(res, "fsyncLock", {
get() {
throw Error(
"fsyncLock is no longer included in the currentOp shell helper, run db.runCommand({currentOp: 1}) instead.",
);
},
});
return res;
} catch (e) {
return {"ok": 0, "code": e.code, "errmsg": "Error executing $currentOp: " + e.message};
}
};
DB.prototype.currentOpCursor = function (arg) {
let q = {};
if (arg) {
if (typeof arg == "object") Object.extend(q, arg);
else if (arg) q["$all"] = true;
}
// Convert the incoming currentOp command into an equivalent aggregate command
// of the form {aggregate:1, pipeline: [{$currentOp: {idleConnections: $all, allUsers:
// !$ownOps, truncateOps: false}}, {$match: {<user-defined filter>}}], cursor:{}}.
let pipeline = [];
let currOpArgs = {};
let currOpStage = {"$currentOp": currOpArgs};
currOpArgs["allUsers"] = !q["$ownOps"];
currOpArgs["idleConnections"] = !!q["$all"];
currOpArgs["truncateOps"] = false;
pipeline.push(currOpStage);
let matchArgs = {};
let matchStage = {"$match": matchArgs};
for (const fieldname of Object.keys(q)) {
if (fieldname !== "$all" && fieldname !== "$ownOps" && fieldname !== "$truncateOps") {
matchArgs[fieldname] = q[fieldname];
}
}
pipeline.push(matchStage);
// The legacy db.currentOp() shell helper ignored any explicitly set read preference and used
// the default, with the ability to also run on secondaries. To preserve this behavior we will
// run the aggregate with read preference "primaryPreferred".
return this.getSiblingDB("admin").aggregate(pipeline, {"$readPreference": {"mode": "primaryPreferred"}});
};
DB.prototype.killOp = function (op) {
if (!op) throw Error("no opNum to kill specified");
return this.adminCommand({"killOp": 1, op});
};
DB.prototype.killOP = DB.prototype.killOp;
DB.tsToSeconds = function (x) {
if (x.t && x.i) return x.t;
return x / 4294967296; // low 32 bits are ordinal #s within a second
};
/**
Get a replication log information summary.
<p>
This command is for the database/cloud administer and not applicable to most databases.
It is only used with the local database. One might invoke from the JS shell:
<pre>
use local
db.getReplicationInfo();
</pre>
* @return Object timeSpan: time span of the oplog from start to end if secondary is more out
* of date than that, it can't recover without a complete resync
*/
DB.prototype.getReplicationInfo = function () {
let localdb = this.getSiblingDB("local");
let result = {};
let oplog;
let localCollections = localdb.getCollectionNames();
if (localCollections.indexOf("oplog.rs") >= 0) {
oplog = "oplog.rs";
} else {
result.errmsg = "replication not detected";
return result;
}
let ol = localdb.getCollection(oplog);
let ol_stats = ol.stats();
if (ol_stats && ol_stats.maxSize) {
result.logSizeMB = ol_stats.maxSize / (1024 * 1024);
} else {
result.errmsg =
"Could not get stats for local." + oplog + " collection. " + "collstats returned: " + tojson(ol_stats);
return result;
}
result.usedMB = ol_stats.size / (1024 * 1024);
result.usedMB = Math.ceil(result.usedMB * 100) / 100;
let firstc = ol.find().sort({$natural: 1}).limit(1);
let lastc = ol.find().sort({$natural: -1}).limit(1);
if (!firstc.hasNext() || !lastc.hasNext()) {
result.errmsg = "objects not found in local.oplog.$main -- is this a new and empty db instance?";
result.oplogMainRowCount = ol.count();
return result;
}
let first = firstc.next();
let last = lastc.next();
let tfirst = first.ts;
let tlast = last.ts;
if (tfirst && tlast) {
tfirst = DB.tsToSeconds(tfirst);
tlast = DB.tsToSeconds(tlast);
result.timeDiff = tlast - tfirst;
result.timeDiffHours = Math.round(result.timeDiff / 36) / 100;
result.tFirst = new Date(tfirst * 1000).toString();
result.tLast = new Date(tlast * 1000).toString();
result.now = Date();
} else {
result.errmsg = "ts element not found in oplog objects";
}
return result;
};
DB.prototype.printReplicationInfo = function () {
let result = this.getReplicationInfo();
if (result.errmsg) {
let reply, isPrimary;
if (this.getMongo().getApiParameters().apiVersion) {
reply = this.hello();
isPrimary = reply.isWritablePrimary;
} else {
reply = this.isMaster();
isPrimary = reply.ismaster;
}
if (reply.arbiterOnly) {
print("cannot provide replication status from an arbiter.");
return;