-
Notifications
You must be signed in to change notification settings - Fork 0
/
.mongorc.js
1767 lines (1524 loc) · 58.1 KB
/
.mongorc.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
/*
*
* Mongo-Hacker
* MongoDB Shell Enhancements for Hackers
*
* Tyler J. Brock - 2013 - 2019
*
* http://tylerbrock.github.com/mongo-hacker
*
*/
mongo_hacker_config = {
verbose_shell: true, // additional verbosity
index_paranoia: false, // querytime explain
enhance_api: true, // additonal api extensions
indent: 2, // number of spaces for indent
sort_keys: false, // sort the keys in documents when displayed
uuid_type: 'default', // 'java', 'c#', 'python' or 'default'
banner_message: 'Mongo-Hacker ', // banner message
version: '0.1.1', // current mongo-hacker version
show_banner: true, // show mongo-hacker version banner on startup
use_color: true, // use color highlighting if possible
force_color: false, // force color even if Mongo Hacker thinks it won't work
windows_warning: true, // show warning banner regarding color support for Windows
count_deltas: false, // "count documents" shows deltas with previous counts
column_separator: '→', // separator used when printing padded/aligned columns
value_separator: '/', // separator used when merging padded/aligned values
dbref: {
extended_info: true, // enable more informations on DBRef
plain: false, // print DBRef as plain JSON object
db_if_differs: false // include $db only if is different than current one
},
// Shell Color Settings
// Colors available: red, green, yellow, blue, magenta, cyan
colors: {
'key': { color: 'gray' },
'number': { color: 'red' },
'boolean': { color: 'blue', bright: true },
'null': { color: 'red', bright: true },
'undefined': { color: 'magenta', bright: true },
'objectid': { color: 'yellow', underline: true },
'string': { color: 'green' },
'binData': { color: 'green', bright: true },
'function': { color: 'magenta' },
'date': { color: 'blue' },
'uuid': { color: 'cyan' },
'databaseNames': { color: 'green', bright: true },
'collectionNames': { color: 'blue', bright: true }
}
}
if (mongo_hacker_config['show_banner']) {
print(mongo_hacker_config['banner_message'] + mongo_hacker_config['version']);
}
if (_isWindows() && mongo_hacker_config['windows_warning']) {
print("\nMongoDB Shell Enhancements for Hackers does not support color highlighting in ");
print("the default Windows Command Prompt. If you are using an alternative console ");
print("such as ConEmu (https://github.com/Maximus5/ConEmu) you may wish to try enabling");
print("highlighting in your mongo_hacker config by setting:");
print("\n\tforce_color: true\n");
print("You can hide this startup warning by setting:");
print("\n\twindows_warning: false\n");
}
if (typeof db !== 'undefined') {
var shell_version = parseFloat(version()).toFixed(1);
var server_version = parseFloat(db.serverBuildInfo().version).toFixed(1);
if ((shell_version < 2.4) || (server_version < 2.4)) {
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
print("Sorry! MongoDB Shell Enhancements for Hackers is only compatible with MongoDB 2.4+");
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
} else if ((shell_version < 3.4) || (server_version < 3.4)) {
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
print("WARNING: Your shell version (" + shell_version + ") " +
"or server version (" + server_version + ") of MongoDB is end of life\n");
print("You should consider upgrading to a supported version (currently 3.4 or newer):");
print(" https://docs.mongodb.com/manual/release-notes/");
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}//----------------------------------------------------------------------------
// Color Functions
//----------------------------------------------------------------------------
__ansi = {
csi: String.fromCharCode(0x1B) + '[',
reset: '0',
text_prop: 'm',
foreground: '3',
bright: '1',
underline: '4',
colors: {
black: '0',
red: '1',
green: '2',
yellow: '3',
blue: '4',
magenta: '5',
cyan: '6',
gray: '7',
}
};
function controlCode( parameters ) {
if ( parameters === undefined ) {
parameters = "";
}
else if (typeof(parameters) == 'object' && (parameters instanceof Array)) {
parameters = parameters.join(';');
}
return __ansi.csi + String(parameters) + String(__ansi.text_prop);
};
function applyColorCode( string, properties, nocolor ) {
// Allow global __colorize default to be overriden
var applyColor = (null == nocolor) ? __colorize : !nocolor;
return applyColor ? controlCode(properties) + String(string) + controlCode() : String(string);
};
function colorize( string, color, nocolor ) {
var params = [];
var code = __ansi.foreground + __ansi.colors[color.color];
params.push(code);
if ( color.bright === true ) params.push(__ansi.bright);
if ( color.underline === true ) params.push(__ansi.underline);
return applyColorCode( string, params, nocolor );
};
function colorizeAll( strings, color, nocolor ) {
return strings.map(function(string) {
return colorize( string, color, nocolor );
});
};
// Begin PS Hack
// Copyright (c) 2016, 2017 Andrew Young
// SPDX-License-Identifier: MIT
var psHack = {
printTableRow: function(row, columnWidths) {
var pad = function(x, i) {
return x.pad(i).slice(-i).toString();
};
var line = "";
for(c in columnWidths) {
line = line + pad(row[c], columnWidths[c]) + " ";
}
print(line);
},
printTable: function(headers, rows) {
// printTable(headers: Array[String], rows: Array[Array[String]])
// Find column widths
var columnWidths = [];
for(c in headers) {
columnWidths[c] = headers[c].length;
}
for(r in rows) {
var row = rows[r];
for (c in headers) {
row[c] = row[c].toString();
columnWidths[c] = Math.max(columnWidths[c], row[c].length);
}
}
// Print Table
var hr = function(l) {
return new Array(l + 1).join("-");
};
var hrs = [];
for(c in columnWidths) {
hrs.push(hr(columnWidths[c]));
}
this.printTableRow(headers, columnWidths);
this.printTableRow(hrs, columnWidths);
var ptr = this.printTableRow;
rows.forEach(function(row) { ptr(row, columnWidths); });
},
// This parses command line options
argumentRegex: /(-|--)(\w+)|"([^"]+)"|'([^']+)'|(\S+)/g,
parseOptions: function(argumentString) {
var options = {};
if(typeof(argumentString) == "string") {
// Arguments outside of options will go here
var optionName = "_args";
options[optionName] = [];
// If we get a -- by itself, we will stop processing arguments.
var stopProcessingArguments = false;
var match = this.argumentRegex.exec(argumentString);
while (match != null) {
if(stopProcessingArguments) {
options["_args"].push(match[0]);
} else if(match[0] == "--") {
stopProcessingArguments = true;
} else if(match[1] != undefined) {
// This is an option name
optionName = match[2];
if (options[optionName] == undefined) {
options[optionName] = [];
}
} else {
for(var i = 3; i < 6; i++) {
// Find the first group that matched
if (match[i] != undefined) {
options[optionName].push(match[i]);
break;
}
}
optionName = "_args";
}
match = this.argumentRegex.exec(argumentString);
}
}
return options;
},
getOptionsAsQuery: function(options, names, f) {
// Returns a query for a given option
values = undefined;
if(typeof(options) == "object" && typeof(names) == "object") {
names.forEach(function(x) {
if (options[x] != undefined) {
if (values == undefined) {
values = [];
}
values = values.concat(options[x]);
}
});
if (values != undefined && typeof(f) == "function") {
values = values.map(f);
}
}
if(values == undefined) {
return undefined;
} else if(values.length == 0) {
return true;
} else if (values.length == 1) {
return values[0];
}
return { $or: values };
},
addOptionsToQuery: function(queryObject, queryName, options, names, f) {
// Adds a given option to the query object
var query = this.getOptionsAsQuery(options, names, f);
if (query != undefined) {
if (typeof(queryName) == "string") {
queryObject[queryName] = query;
}
}
},
ps: function(db, argumentString) {
var headers = [
"Thread ID",
"Description",
"Connection",
"Op ID",
"App Name",
"Client",
"S",
"Active",
"Time",
"WaitLock",
"Operation",
"Plan",
"Namespace"
];
var rows = [];
var options = this.parseOptions(argumentString);
if (options["h"] != undefined || options["help"] != undefined) {
print("Usage: ps [options]");
print("Options:")
print(" -a | --all Show all operations (this overrides all other options)");
print(" -c | --client <ip/hostname> Show process for client*");
print(" -d | --description <description> Show processes with description");
print(" -A | --active Show only active processes");
print(" -r | --running <seconds> Show only processes which have been running for a certain time");
print(" -o | --op <operation> Show commands running a certain operation");
print(" -n | --ns <namespace> Show commands running against a certain namespace*");
print(" -x | --app <app name> Show commands with a matching app name*");
print(" -l | --locks Show commands waiting for a lock");
print(" -C | --collection <name> Search the given collection instead of calling db.currentOp()");
print(" -v | --verbose Print the query that is being run");
print("Note: Options marked with * will return all operations that start with the provided value.");
return;
}
var connectionOptions = {};
if (options["a"] == undefined && options["all"] == undefined) {
connectionOptions.connectionId = { $exists: true };
} else {
connectionOptions["$all"] = true;
}
this.addOptionsToQuery(connectionOptions, "desc", options, ["d","description","desc"]);
this.addOptionsToQuery(connectionOptions, "active", options, ["A","active"]);
this.addOptionsToQuery(connectionOptions, "secs_running", options, ["r","running"], function(x) { return { $gt: x }; });
this.addOptionsToQuery(connectionOptions, "op", options, ["o","op"]);
this.addOptionsToQuery(connectionOptions, "ns", options, ["n","ns"], function(x) { return { $regex: "^" + x.replace(/\$/g, "\\$") } });
this.addOptionsToQuery(connectionOptions, "appName", options, ["x","app"], function(x) { return { $regex: new RegExp(x.replace(/\$/g, "\\$"), "i") } });
this.addOptionsToQuery(connectionOptions, "waitingForLock", options, ["l","locks"]);
var clientQuery = this.getOptionsAsQuery(options, ["c","client"], function(x) { return { $regex: "^" + x } });
if (clientQuery != undefined) {
// This one search two separate fields, which makes it more complicated
var oldQueryString = JSON.stringify(connectionOptions);
var q1 = JSON.parse(oldQueryString);
var q2 = JSON.parse(oldQueryString);
q1.client = clientQuery;
q2.client_s = clientQuery;
connectionOptions = { $or: [ q1, q2 ] };
}
if(options["v"] != undefined || options["verbose"] != undefined) {
print("Query: " + tojson(connectionOptions));
}
var connections = [];
var customCollection = (options["C"] || options["collection"] || [])[0];
if (customCollection != undefined) {
connections = db[customCollection].find(connectionOptions);
} else {
connections = db.currentOp(connectionOptions).inprog;
}
connections.forEach(function(op) {
var threadId = op.threadId || "";
var description = op.desc || "";
var connectionId = op.connectionId || "";
var opId = op.opid || "";
var appName = op.appName || "";
var client = op.client || op.client_s || "";
var isMongos = op.client_s ? "S" : "";
var active = op.active ? "Active" : "Idle";
var time = op.secs_running || "";
var waitingForLock = op.waitingForLock ? "Yes" : "No";
var opName = op.op || "";
var plan = op.planSummary || "";
var ns = op.ns || "";
rows.push([
threadId,
description,
connectionId,
opId,
appName,
client,
isMongos,
active,
time,
waitingForLock,
opName,
plan,
ns
]);
});
this.printTable(headers, rows);
},
kill: function(db, opId) {
return db.killOp(opId);
},
};
function ps(argumentString) {
psHack.ps(db, argumentString);
}
function kill(argumentString) {
psHack.kill(db, argumentString);
}
shellHelper.ps = ps;
shellHelper.kill = kill;
// End PS Hack
//----------------------------------------------------------------------------
// Aggregation API Extensions
//----------------------------------------------------------------------------
// Inject aggregation extension while supporting base API
DBCollection.prototype.aggregate = function( pipeline, aggregateOptions ){
if (pipeline instanceof Array) {
// Expected case for modern usage; skip extra checks
} else if (hasDollar(pipeline) && !(pipeline instanceof Array) ) {
// Support legacy varargs form (2.6 and older) but warn on usage
print("WARNING: Legacy aggregate() syntax does not support passing options.");
print(" Passing the pipeline as an array is recommended.");
pipeline = Array.from(arguments);
aggregateOptions = {};
} else if (pipeline === undefined) {
pipeline = [];
} else {
// Use Mongo Hacker's fluent aggregation API
return new Aggregation( this ).match( pipeline || {} );
}
if (aggregateOptions === undefined) {
aggregateOptions = {};
}
if (aggregateOptions.cursor === undefined){
aggregateOptions.cursor = {batchSize: 1000};
}
const cmdObj = this._makeCommand("aggregate", {pipeline: pipeline});
return this._db._runAggregate(cmdObj, aggregateOptions);
};
// Helper method for determining if parameter has dollar signs
function hasDollar(fields){
for (k in fields){
if(k.indexOf('$') !== -1){
return true;
};
};
return false;
}
//----------------------------------------------------------------------------
// Aggregation Object
//----------------------------------------------------------------------------
Aggregation = function( collection, fields ){
this._collection = collection;
this._pipeline = [];
this._options = {};
};
Aggregation.prototype.hasNext = function() {
if (this._results == undefined) {
return;
} else {
return this._results.hasNext();
}
};
// Alias the cursor API's hasNext() in case any Mongo Hacker users relied on this
Aggregation.prototype.has_next = Aggregation.prototype.hasNext;
Aggregation.prototype.next = function() {
if (this._results === undefined) {
return;
} else {
return this._results.next();
}
};
Aggregation.prototype.execute = function() {
var aggregateOptions = this._options;
if (aggregateOptions === undefined) {
aggregateOptions = {};
}
if (aggregateOptions.cursor === undefined){
aggregateOptions.cursor = {batchSize: 1000};
}
var res = this._collection.aggregate(this._pipeline, aggregateOptions);
this._results = res;
return;
};
Aggregation.prototype.shellPrint = function() {
if (this._results === undefined) {
this.execute();
}
try {
var i = 0;
while (this.hasNext() && (i < DBQuery.shellBatchSize) ) {
var result = this.next();
printjson( result );
i++;
}
if ( this.hasNext() ) {
print ( "Type \"it\" for more" );
___it___ = this;
}
else {
___it___ = null;
}
}
catch ( e ) {
print( e );
}
};
Aggregation.prototype.project = function( fields ) {
if ( ! fields ) {
throw "project needs fields";
}
this._pipeline.push({ "$project": fields });
return this;
};
Aggregation.prototype.find = function( criteria ) {
if ( ! criteria ) {
throw "match needs a query object";
}
this._pipeline.push({ "$match": criteria });
return this;
};
Aggregation.prototype.match = function( criteria ) {
if ( ! criteria ) {
throw "match needs a query object";
}
this._pipeline.push({ "$match": criteria });
return this;
};
Aggregation.prototype.limit = function( limit ) {
if ( ! limit ) {
throw "limit needs an integer indicating the limit";
}
this._pipeline.push({ "$limit": limit });
return this;
};
Aggregation.prototype.skip = function( skip ) {
if ( ! skip ) {
throw "skip needs an integer indicating the number to skip";
}
this._pipeline.push({ "$skip": skip });
return this;
};
Aggregation.prototype.unwind = function( field ) {
if ( ! field ) {
throw "unwind needs the key of an array field to unwind";
}
this._pipeline.push({ "$unwind": "$" + field });
return this;
};
Aggregation.prototype.group = function( group_expression ) {
if ( ! group_expression ) {
throw "group needs an group expression";
}
this._pipeline.push({ "$group": group_expression });
return this;
};
Aggregation.prototype.sort = function( sort ) {
if ( ! sort ) {
throw "sort needs a sort document";
}
this._pipeline.push({ "$sort": sort });
return this;
};
Aggregation.prototype.geoNear = function( options ) {
if ( ! options ) {
throw "geo near requires options"
}
this._pipeline.push({ "$geoNear": options });
return this;
};
Aggregation.prototype.readPreference = function( mode ) {
this._readPreference = mode;
return this;
};
Aggregation.prototype.explain = function( ) {
this._options['explain'] = true;
return this;
};
// Override group because map/reduce style is deprecated
DBCollection.prototype.agg_group = function( name, group_field, operation, op_value, filter ) {
var ops = [];
var group_op = { $group: { _id: '$' + group_field } };
if (filter !== undefined) {
ops.push({ '$match': filter });
}
group_op['$group'][name] = { };
group_op['$group'][name]['$' + operation] = op_value;
ops.push(group_op);
return this.aggregate(ops);
};
// Function that groups and counts by group after applying filter
DBCollection.prototype.gcount = function( group_field, filter ) {
return this.agg_group('count', group_field, 'sum', 1, filter);
};
// Function that groups and sums sum_field after applying filter
DBCollection.prototype.gsum = function( group_field, sum_field, filter ) {
return this.agg_group('sum', group_field, 'sum', '$' + sum_field, filter);
};
// Function that groups and averages avg_feld after applying filter
DBCollection.prototype.gavg = function( group_field, avg_field, filter ) {
return this.agg_group('avg', group_field, 'avg', '$' + avg_field, filter);
};
function base64ToHex(base64) {
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var hexDigits = "0123456789abcdef";
var hex = "";
for (var i = 0; i < 24; ) {
var e1 = base64Digits.indexOf(base64[i++]);
var e2 = base64Digits.indexOf(base64[i++]);
var e3 = base64Digits.indexOf(base64[i++]);
var e4 = base64Digits.indexOf(base64[i++]);
var c1 = (e1 << 2) | (e2 >> 4);
var c2 = ((e2 & 15) << 4) | (e3 >> 2);
var c3 = ((e3 & 3) << 6) | e4;
hex += hexDigits[c1 >> 4];
hex += hexDigits[c1 & 15];
if (e3 != 64) {
hex += hexDigits[c2 >> 4];
hex += hexDigits[c2 & 15];
}
if (e4 != 64) {
hex += hexDigits[c3 >> 4];
hex += hexDigits[c3 & 15];
}
}
return hex;
}
function hexToBase64(hex) {
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64 = "";
var group;
for (var i = 0; i < 30; i += 6) {
group = parseInt(hex.substr(i, 6), 16);
base64 += base64Digits[(group >> 18) & 0x3f];
base64 += base64Digits[(group >> 12) & 0x3f];
base64 += base64Digits[(group >> 6) & 0x3f];
base64 += base64Digits[group & 0x3f];
}
group = parseInt(hex.substr(30, 2), 16);
base64 += base64Digits[(group >> 2) & 0x3f];
base64 += base64Digits[(group << 4) & 0x3f];
base64 += "==";
return base64;
}
var platformSpecificUuidModifications = {
"java": function (hex) {
var msb = hex.substr(0, 16);
var lsb = hex.substr(16, 16);
msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2)
+ msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2);
lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2)
+ lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2);
return msb + lsb;
},
"c#": function (hex) {
return hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2)
+ hex.substr(10, 2) + hex.substr(8, 2) + hex.substr(14, 2) + hex.substr(12, 2)
+ hex.substr(16, 16);
},
"python": function (hex) {
return hex;
},
"default": function (hex) {
return hex;
}
};
function UUID(uuid, type) {
var hex = uuid.replace(/[{}-]/g, "");
var typeNum = 4;
if (type != undefined) {
typeNum = 3;
hex = platformSpecificUuidModifications[type](hex);
}
return new BinData(typeNum, hexToBase64(hex));
}
function uuidToString(uuid, uuidType) {
var uuidType = uuidType || mongo_hacker_config['uuid_type'];
var hex = platformSpecificUuidModifications[uuidType](base64ToHex(uuid.base64()));
return hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4)
+ '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
}
// Better show dbs
shellHelper.show = function () {
var show = shellHelper.show;
return function (what) {
assert(typeof what == "string");
if (what == "collections" || what == "tables") {
var collectionNames = db.getCollectionNames();
var collectionStats = collectionNames.map(function (name) {
var stats = db.getCollection(name).stats();
if (stats.ok) {
var size = (stats.size / 1024 / 1024).toFixed(3);
return (size + "MB");
} else if (stats.code === 166) {
return "VIEW";
} else {
return "ERR:" + stats.code;
}
});
var collectionStorageSizes = collectionNames.map(function (name) {
var stats = db.getCollection(name).stats();
if (stats.ok) {
var storageSize = (stats.storageSize / 1024 / 1024).toFixed(3);
return (storageSize + "MB");
}
return "";
});
collectionNames = colorizeAll(collectionNames, mongo_hacker_config['colors']['collectionNames']);
printPaddedColumns(collectionNames, collectionStats, collectionStorageSizes);
return "";
}
if (what == "dbs" || what == "databases") {
var databases = db.getMongo().getDBs().databases.sort(function(a, b) { return a.name.localeCompare(b.name) });
var databaseNames = databases.map(function(db) {
return db.name;
});
var databaseSizes = databases.map(function(db) {
var sizeInGigaBytes = (db.sizeOnDisk / 1024 / 1024 / 1024).toFixed(3);
return (db.sizeOnDisk > 1) ? (sizeInGigaBytes + "GB") : "(empty)";
});
databaseNames = colorizeAll(databaseNames, mongo_hacker_config['colors']['databaseNames']);
printPaddedColumns(databaseNames, databaseSizes);
return "";
}
return show(what);
}
}();
//----------------------------------------------------------------------------
// findAndModify Helper
//----------------------------------------------------------------------------
DBQuery.prototype._findAndModify = function( options ) {
var findAndModify = {
'findandmodify': this._collection.getName(),
'query': this._query,
'new': true,
'fields': this._fields,
'upsert': this._upsert || false,
'sort': this._query.orderby || {},
};
for (var key in options){
findAndModify[key] = options[key];
};
var result = this._db.runCommand( findAndModify );
if ( ! result.ok ){
throw "findAndModifyFailed failed: " + tojson( result );
};
return result.value;
};
//----------------------------------------------------------------------------
// findAndModify Terminal Variants
//----------------------------------------------------------------------------
DBQuery.prototype.updateAndGet = function( update ) {
return this._findAndModify({ 'update': update });
};
DBQuery.prototype.getAndUpdate = function( update ) {
return this._findAndModify({ 'update': update, 'new': false });
};
DBQuery.prototype.replaceAndGet = function( replacement ) {
return this._findAndModify({ 'update': replacement });
};
DBQuery.prototype.getAndReplace = function( replacement ) {
return this._findAndModify({ 'update': replacement, 'new': false });
};
DBQuery.prototype.getAndRemove = function() {
return this._findAndModify({ 'remove': true })
};// Improve the default prompt with hostname, process type, and version
prompt = function() {
var serverstatus = db.serverStatus();
var host = serverstatus.host.split('.')[0];
var process = serverstatus.process;
var version = db.serverBuildInfo().version;
var repl_set = db._adminCommand({"replSetGetStatus": 1}).ok !== 0;
var rs_state = '';
if(repl_set) {
var status = rs.status();
var members = status.members;
var rs_name = status.set;
for(var i = 0; i<members.length; i++){
if(members[i].self === true){
rs_state = '[' + members[i].stateStr + ':' + rs_name + ']';
}
};
}
var state = isMongos() ? '[mongos]' : rs_state;
return '(' + process + '-' + version + ')' + state + ' ' + db + '> ';
};
function listDbs(){
return db.adminCommand("listDatabases").databases.map(function(d){return d.name});
}
this.__proto__.constructor.autocomplete = listDbs;DBRef.prototype.__toString = DBRef.prototype.toString;
DBRef.prototype.toString = function () {
var org = this.__toString();
var config = mongo_hacker_config.dbref;
if (!config.extended_info) {
return org;
}
var additional = {};
var o = this;
for (var p in o) {
if (typeof o[p] === 'function') {
continue;
}
if (!config.plain && (p === '$ref' || p === '$id')) {
continue;
}
if (config.db_if_differs && p === '$db' && o[p] === db.getName()) {
continue;
}
additional[p] = o[p];
}
if (config.plain) {
return tojsonObject(additional, undefined, true);
}
return Object.keys(additional).length
? (org.slice(0, -1) + ", " + tojsonObject(additional, undefined, true) + ")")
: org;
};
function runMatch(cmd, args, regexp) {
clearRawMongoProgramOutput();
if (args) {
run(cmd, args);
} else {
run(cmd);
}
var output = rawMongoProgramOutput();
return output.match(regexp);
};
function getEnv(env_var) {
var env_regex = new RegExp(' ' + env_var + '=(.*)');
return runMatch('env', '', env_regex)[1];
};
function getVersion() {
var regexp = /version: (\d).(\d).(\d)/;
return runMatch('mongo', '--version', regexp).slice(1, 4);
};
function isMongos() {
return db.isMaster().msg == 'isdbgrid';
};
function getSlowms(){
if (!isMongos()){
var current_version = parseFloat(db.serverBuildInfo().version).toFixed(2);
if (current_version >= 4.0) {
// The `profile` command can block with pending transactions in 4.0+ (#193)
return 100;
}
var res = db._dbCommand({profile: -1});
return (res.ok ? res.slowms : 100);
} else {
return 100;
}
};
function maxLength(listOfNames) {
return listOfNames.reduce(function(maxLength, name) {
return (name.length > maxLength) ? name.length : maxLength ;
}, 0);
};
function printPaddedColumns() {
var columnWidths = Array.prototype.map.call(
arguments,
function(column) {
return maxLength(column);
}
);
for (i = 0; i < arguments[0].length; i++) {
row = "";
for (j = 0; j < arguments.length; j++) {
var separator = ""
var val = arguments[j][i].toString();
if (!val && j >= arguments.length - 1) { continue; }
val = val.pad(columnWidths[j], (j == 0));
if (j > 0) {
separator = " " + ((j == 1) ?
mongo_hacker_config['column_separator'] :
mongo_hacker_config['value_separator']
) + " ";
}
row += separator + val;
}
print(row);
}
return null;
};
function runOnDbs(regexp, callback) {
var originalDb = db.getName();
db.getMongo().getDBs().databases.filter(function(db) {
return db.name.match(regexp); }
).forEach(function(dbEntry) {
db = db.getSiblingDB(dbEntry.name);
callback(db);
});
db = db.getSiblingDB(originalDb);
}
shellHelper.find = function (query) {
assert(typeof query == "string");
var args = query.split( /\s+/ );
query = args[0];
args = args.splice(1);
if (query !== "") {
var regexp = new RegExp(query, "i");
var result = db.runCommand("listCommands");
for (var command in result.commands) {
var commandObj = result.commands[command];
var help = commandObj.help;
if (commandObj.help.indexOf('\n') != -1 ) {
help = commandObj.help.substring(0, commandObj.help.lastIndexOf('\n'));
}
if (regexp.test(command) || regexp.test(help)) {
var numSpaces = 30 - command.length;
print(colorize(command, {color: 'green'}), Array(numSpaces).join(" "), "-", help);
}
}
}
};
__indent = Array(mongo_hacker_config.indent + 1).join(' ');
__colorize = mongo_hacker_config['use_color'];
// Disable color for terminals that aren't likely to support ANSI color codes
if (__colorize && !mongo_hacker_config['force_color']) {
if (_isWindows()) {
__colorize = false;
} else if (typeof(isInteractive) === typeof(Function)) {
// Requires MongoDB 4.2+ shell
__colorize = isInteractive();
}
}
ObjectId.prototype.toString = function() {
return this.str;
};
ObjectId.prototype.tojson = function(indent, nolint) {
return tojson(this);
};
var dateToJson = Date.prototype.tojson;
Date.prototype.tojson = function(indent, nolint, nocolor) {
var isoDateString = dateToJson.call(this);
var dateString = isoDateString.substring(8, isoDateString.length-1);
var isodate = colorize(dateString, mongo_hacker_config.colors.date, nocolor);
return 'ISODate(' + isodate + ')';
};
Array.tojson = function( a , indent , nolint, nocolor ){
var lineEnding = nolint ? " " : "\n";
if (!indent)
indent = "";