Guest User

Untitled

a guest
Dec 14th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.78 KB | None | 0 0
  1. __ansi = {
  2. csi: String.fromCharCode(0x1B) + '[',
  3. reset: '0',
  4. text_prop: 'm',
  5. foreground: '3',
  6. bright: '1',
  7. underline: '4',
  8.  
  9. colors: {
  10. red: '1',
  11. green: '2',
  12. yellow: '3',
  13. blue: '4',
  14. magenta: '5',
  15. cyan: '6'
  16. }
  17. }
  18.  
  19. if (_isWindows()) {
  20. print("\nSorry! MongoDB Shell Enhancements for Hackers isn't compatible with Windows.\n");
  21. }
  22.  
  23. var ver = db.version().split(".");
  24. if ( ver[0] <= parseInt("2") && ver[1] < parseInt("2") ) {
  25. print(colorize("\nSorry! Mongo version 2.2.x and above is required! Please upgrade.\n", "red", true));
  26. }
  27.  
  28. setVerboseShell(true);
  29. setIndexParanoia(true);
  30. setAutoMulti(true);
  31.  
  32. __indent = " "
  33.  
  34. function setIndexParanoia( value ) {
  35. if( value == undefined ) value = true;
  36. _indexParanoia = value;
  37. }
  38.  
  39. function setAutoMulti( value ) {
  40. if( value == undefined ) value = true;
  41. _autoMulti = value;
  42. }
  43.  
  44. function controlCode( parameters ) {
  45. if ( parameters == undefined ) {
  46. parameters = "";
  47. }
  48. else if (typeof(parameters) == 'object' && (parameters instanceof Array)) {
  49. parameters = parameters.join(';');
  50. }
  51.  
  52. return __ansi.csi + String(parameters) + String(__ansi.text_prop);
  53. }
  54.  
  55. function applyColorCode( string, properties ) {
  56. return controlCode(properties) + String(string) + controlCode();
  57. }
  58.  
  59. function colorize( string, color, bright, underline ) {
  60. var params = [];
  61. var code = __ansi.foreground + __ansi.colors[color];
  62.  
  63. params.push(code);
  64.  
  65. if ( bright == true ) params.push(__ansi.bright);
  66. if ( underline == true ) params.push(__ansi.underline);
  67.  
  68. return applyColorCode( string, params );
  69. }
  70.  
  71. ObjectId.prototype.toString = function() {
  72. return this.str;
  73. }
  74.  
  75. ObjectId.prototype.tojson = function(indent, nolint) {
  76. return tojson(this);
  77. }
  78.  
  79. Date.prototype.tojson = function() {
  80.  
  81. var UTC = Date.printAsUTC ? 'UTC' : '';
  82.  
  83. var year = this['get'+UTC+'FullYear']().zeroPad(4);
  84. var month = (this['get'+UTC+'Month']() + 1).zeroPad(2);
  85. var date = this['get'+UTC+'Date']().zeroPad(2);
  86. var hour = this['get'+UTC+'Hours']().zeroPad(2);
  87. var minute = this['get'+UTC+'Minutes']().zeroPad(2);
  88. var sec = this['get'+UTC+'Seconds']().zeroPad(2)
  89.  
  90. if (this['get'+UTC+'Milliseconds']())
  91. sec += '.' + this['get'+UTC+'Milliseconds']().zeroPad(3)
  92.  
  93. var ofs = 'Z';
  94. if (!Date.printAsUTC) {
  95. var ofsmin = this.getTimezoneOffset();
  96. if (ofsmin != 0){
  97. ofs = ofsmin > 0 ? '-' : '+'; // This is correct
  98. ofs += (ofsmin/60).zeroPad(2)
  99. ofs += (ofsmin%60).zeroPad(2)
  100. }
  101. }
  102.  
  103. var date = colorize('"' + year + month + date + 'T' + hour +':' + minute + ':' + sec + ofs + '"', "cyan");
  104. return 'ISODate(' + date + ')';
  105. }
  106.  
  107. Array.tojson = function( a , indent , nolint ){
  108. var lineEnding = nolint ? " " : "\n";
  109.  
  110. if (!indent)
  111. indent = "";
  112.  
  113. if ( nolint )
  114. indent = "";
  115.  
  116. if (a.length == 0) {
  117. return "[ ]";
  118. }
  119.  
  120. var s = "[" + lineEnding;
  121. indent += __indent;
  122. for ( var i=0; i<a.length; i++){
  123. s += indent + tojson( a[i], indent , nolint );
  124. if ( i < a.length - 1 ){
  125. s += "," + lineEnding;
  126. }
  127. }
  128. if ( a.length == 0 ) {
  129. s += indent;
  130. }
  131.  
  132. indent = indent.substring(__indent.length);
  133. s += lineEnding+indent+"]";
  134. return s;
  135. }
  136.  
  137. tojson = function( x, indent , nolint ) {
  138. if ( x === null )
  139. return colorize("null", "red", true);
  140.  
  141. if ( x === undefined )
  142. return colorize("undefined", "magenta", true);
  143.  
  144. if ( x.isObjectId ) {
  145. return 'ObjectId(' + colorize('"' + x.str + '"', "green", false, true) + ')';
  146. }
  147.  
  148. if (!indent)
  149. indent = "";
  150.  
  151. switch ( typeof x ) {
  152. case "string": {
  153. var s = "\"";
  154. for ( var i=0; i<x.length; i++ ){
  155. switch (x[i]){
  156. case '"': s += '\\"'; break;
  157. case '\\': s += '\\\\'; break;
  158. case '\b': s += '\\b'; break;
  159. case '\f': s += '\\f'; break;
  160. case '\n': s += '\\n'; break;
  161. case '\r': s += '\\r'; break;
  162. case '\t': s += '\\t'; break;
  163.  
  164. default: {
  165. var code = x.charCodeAt(i);
  166. if (code < 0x20){
  167. s += (code < 0x10 ? '\\u000' : '\\u00') + code.toString(16);
  168. } else {
  169. s += x[i];
  170. }
  171. }
  172. }
  173. }
  174. s += "\""
  175. return colorize(s, "green", true);
  176. }
  177. case "number":
  178. return colorize(x, "red")
  179. case "boolean":
  180. return colorize("" + x, "blue");
  181. case "object": {
  182. var s = tojsonObject( x, indent , nolint );
  183. if ( ( nolint == null || nolint == true ) && s.length < 80 && ( indent == null || indent.length == 0 ) ){
  184. s = s.replace( /[\s\r\n ]+/gm , " " );
  185. }
  186. return s;
  187. }
  188. case "function":
  189. return colorize(x.toString(), "magenta")
  190. default:
  191. throw "tojson can't handle type " + ( typeof x );
  192. }
  193.  
  194. }
  195.  
  196. tojsonObject = function( x, indent , nolint ) {
  197. var lineEnding = nolint ? " " : "\n";
  198. var tabSpace = nolint ? "" : __indent;
  199.  
  200. assert.eq( ( typeof x ) , "object" , "tojsonObject needs object, not [" + ( typeof x ) + "]" );
  201.  
  202. if (!indent)
  203. indent = "";
  204.  
  205. if ( typeof( x.tojson ) == "function" && x.tojson != tojson ) {
  206. return x.tojson(indent,nolint);
  207. }
  208.  
  209. if ( x.constructor && typeof( x.constructor.tojson ) == "function" && x.constructor.tojson != tojson ) {
  210. return x.constructor.tojson( x, indent , nolint );
  211. }
  212.  
  213. if ( x.toString() == "[object MaxKey]" )
  214. return "{ $maxKey : 1 }";
  215. if ( x.toString() == "[object MinKey]" )
  216. return "{ $minKey : 1 }";
  217.  
  218. var s = "{" + lineEnding;
  219.  
  220. // push one level of indent
  221. indent += tabSpace;
  222.  
  223. var total = 0;
  224. for ( var k in x ) total++;
  225. if ( total == 0 ) {
  226. s += indent + lineEnding;
  227. }
  228.  
  229. var keys = x;
  230. if ( typeof( x._simpleKeys ) == "function" )
  231. keys = x._simpleKeys();
  232. var num = 1;
  233. for ( var k in keys ){
  234.  
  235. var val = x[k];
  236. if ( val == DB.prototype || val == DBCollection.prototype )
  237. continue;
  238.  
  239. s += indent + colorize("\"" + k + "\"", "yellow") + ": " + tojson( val, indent , nolint );
  240. if (num != total) {
  241. s += ",";
  242. num++;
  243. }
  244. s += lineEnding;
  245. }
  246.  
  247. // pop one level of indent
  248.  
  249. indent = indent.substring(__indent.length);
  250. return s + indent + "}";
  251. }
  252.  
  253. // Hardcode multi update -- now you only need to remember upsert
  254. DBCollection.prototype.update = function( query , obj , upsert, multi ) {
  255. assert( query , "need a query" );
  256. assert( obj , "need an object" );
  257.  
  258. var firstKey = null;
  259. for (var k in obj) { firstKey = k; break; }
  260.  
  261. if (firstKey != null && firstKey[0] == '$') {
  262. // for mods we only validate partially, for example keys may have dots
  263. this._validateObject( obj );
  264. } else {
  265. // we're basically inserting a brand new object, do full validation
  266. this._validateForStorage( obj );
  267. }
  268.  
  269. // can pass options via object for improved readability
  270. if ( typeof(upsert) === 'object' ) {
  271. assert( multi === undefined, "Fourth argument must be empty when specifying upsert and multi with an object." );
  272.  
  273. opts = upsert;
  274. multi = opts.multi;
  275. upsert = opts.upsert;
  276. }
  277.  
  278. this._mongo.update( this._fullName , query , obj , upsert ? true : false , _autoMulti ? true : multi );
  279. }
  280.  
  281. // Override group because map/reduce style is deprecated
  282. DBCollection.prototype.agg_group = function( name, group_field, operation, op_value, filter ) {
  283. var ops = [];
  284. var group_op = { $group: { _id: '$' + group_field } };
  285.  
  286. if (filter != undefined) {
  287. ops.push({ '$match': filter })
  288. }
  289.  
  290. group_op['$group'][name] = { };
  291. group_op['$group'][name]['$' + operation] = op_value
  292. ops.push(group_op);
  293.  
  294. return this.aggregate(ops);
  295. }
  296.  
  297. // Function that groups and counts by group after applying filter
  298. DBCollection.prototype.gcount = function( group_field, filter ) {
  299. return this.agg_group('count', group_field, 'sum', 1, filter);
  300. }
  301.  
  302. // Function that groups and sums sum_field after applying filter
  303. DBCollection.prototype.gsum = function( group_field, sum_field, filter ) {
  304. return this.agg_group('sum', group_field, 'sum', '$' + sum_field, filter);
  305. }
  306.  
  307. // Function that groups and averages avg_feld after applying filter
  308. DBCollection.prototype.gavg = function( group_field, avg_field, filter ) {
  309. return this.agg_group('avg', group_field, 'avg', '$' + avg_field, filter);
  310. }
  311.  
  312. // Improve the default prompt with process and db name
  313. prompt = function() {
  314. var serverstatus = db.serverStatus();
  315. var host = serverstatus.host.split('.')[0];
  316. var process = serverstatus.process;
  317. var version = db.serverBuildInfo().version;
  318. return process + '~ db:' + db + ' >> ';
  319. }
  320.  
  321. DBQuery.prototype.shellPrint = function(){
  322. try {
  323. var start = new Date().getTime();
  324. var n = 0;
  325. while ( this.hasNext() && n < DBQuery.shellBatchSize ){
  326. var s = this._prettyShell ? tojson( this.next() ) : tojson( this.next() , "" , true );
  327. print( s );
  328. n++;
  329. }
  330.  
  331. var output = []
  332.  
  333. if (typeof _verboseShell !== 'undefined' && _verboseShell) {
  334. var time = new Date().getTime() - start;
  335. var slowms = this._db.setProfilingLevel().slowms;
  336. var fetched = "Fetched " + n + " record(s) in ";
  337. if (time > slowms) {
  338. fetched += colorize(time + "ms", "red", true);
  339. } else {
  340. fetched += colorize(time + "ms", "green", true);
  341. }
  342. output.push(fetched);
  343. }
  344. if (typeof _indexParanoia !== 'undefined' && _indexParanoia) {
  345. var explain = this.clone();
  346. explain._ensureSpecial();
  347. explain._query.$explain = true;
  348. explain._limit = Math.abs(n._limit) * -1;
  349. var result = explain.next();
  350. var type = result.cursor;
  351. var index_use = "Index["
  352. if (type == "BasicCursor") {
  353. index_use += colorize( "none", "red", true);
  354. } else {
  355. if(result.cursor){
  356. index_use += colorize( result.cursor.substring(12), "green", true );
  357. }
  358. }
  359. index_use += "]";
  360. output.push(index_use);
  361. }
  362. if ( this.hasNext() ) {
  363. ___it___ = this;
  364. output.push("More[" + colorize("true", "green", true) + "]");
  365. }
  366. else {
  367. ___it___ = null;
  368. output.push("More[" + colorize("false", "red", true) + "]");
  369. }
  370. print(output.join(" -- "));
  371. }
  372. catch ( e ){
  373. print( e );
  374. }
  375.  
  376. }
  377.  
  378. // Set print to .pretty() by default
  379. DBQuery.prototype._prettyShell = true
Add Comment
Please, Sign In to add comment