#include "bson/stringdata.h" namespace mongo { struct JSFile{ const char* name; const StringData& source; }; namespace JSFiles{ const StringData _jscode_raw_utils = "__quiet = false;\n" "__magicNoPrint = { __magicNoPrint : 1111 }\n" "\n" "chatty = function(s){\n" "if ( ! __quiet )\n" "print( s );\n" "}\n" "\n" "friendlyEqual = function( a , b ){\n" "if ( a == b )\n" "return true;\n" "\n" "if ( tojson( a ) == tojson( b ) )\n" "return true;\n" "\n" "return false;\n" "}\n" "\n" "printStackTrace = function(){\n" "try{\n" "throw new Error(\"Printing Stack Trace\");\n" "} catch (e) {\n" "print(e.stack);\n" "}\n" "}\n" "\n" "doassert = function (msg) {\n" "if (msg.indexOf(\"assert\") == 0)\n" "print(msg);\n" "else\n" "print(\"assert: \" + msg);\n" "printStackTrace();\n" "throw msg;\n" "}\n" "\n" "assert = function( b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( b )\n" "return;\n" "\n" "doassert( msg == undefined ? \"assert failed\" : \"assert failed : \" + msg );\n" "}\n" "\n" "assert.automsg = function( b ) {\n" "assert( eval( b ), b );\n" "}\n" "\n" "assert._debug = false;\n" "\n" "assert.eq = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( a == b )\n" "return;\n" "\n" "if ( ( a != null && b != null ) && friendlyEqual( a , b ) )\n" "return;\n" "\n" "doassert( \"[\" + tojson( a ) + \"] != [\" + tojson( b ) + \"] are not equal : \" + msg );\n" "}\n" "\n" "assert.eq.automsg = function( a, b ) {\n" "assert.eq( eval( a ), eval( b ), \"[\" + a + \"] != [\" + b + \"]\" );\n" "}\n" "\n" "assert.neq = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "if ( a != b )\n" "return;\n" "\n" "doassert( \"[\" + a + \"] != [\" + b + \"] are equal : \" + msg );\n" "}\n" "\n" "assert.repeat = function( f, msg, timeout, interval ) {\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "var start = new Date();\n" "timeout = timeout || 30000;\n" "interval = interval || 200;\n" "var last;\n" "while( 1 ) {\n" "\n" "if ( typeof( f ) == \"string\" ){\n" "if ( eval( f ) )\n" "return;\n" "}\n" "else {\n" "if ( f() )\n" "return;\n" "}\n" "\n" "if ( ( new Date() ).getTime() - start.getTime() > timeout )\n" "break;\n" "sleep( interval );\n" "}\n" "}\n" "\n" "assert.soon = function( f, msg, timeout /*ms*/, interval ) {\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "var start = new Date();\n" "timeout = timeout || 30000;\n" "interval = interval || 200;\n" "var last;\n" "while( 1 ) {\n" "\n" "if ( typeof( f ) == \"string\" ){\n" "if ( eval( f ) )\n" "return;\n" "}\n" "else {\n" "if ( f() )\n" "return;\n" "}\n" "\n" "if ( ( new Date() ).getTime() - start.getTime() > timeout )\n" "doassert( \"assert.soon failed: \" + f + \", msg:\" + msg );\n" "sleep( interval );\n" "}\n" "}\n" "\n" "assert.throws = function( func , params , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( params && typeof( params ) == \"string\" )\n" "throw \"2nd argument to assert.throws has to be an array\"\n" "\n" "try {\n" "func.apply( null , params );\n" "}\n" "catch ( e ){\n" "return e;\n" "}\n" "\n" "doassert( \"did not throw exception: \" + msg );\n" "}\n" "\n" "assert.throws.automsg = function( func, params ) {\n" "assert.throws( func, params, func.toString() );\n" "}\n" "\n" "assert.commandWorked = function( res , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( res.ok == 1 )\n" "return;\n" "\n" "doassert( \"command failed: \" + tojson( res ) + \" : \" + msg );\n" "}\n" "\n" "assert.commandFailed = function( res , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( res.ok == 0 )\n" "return;\n" "\n" "doassert( \"command worked when it should have failed: \" + tojson( res ) + \" : \" + msg );\n" "}\n" "\n" "assert.isnull = function( what , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( what == null )\n" "return;\n" "\n" "doassert( \"supposed to null (\" + ( msg || \"\" ) + \") was: \" + tojson( what ) );\n" "}\n" "\n" "assert.lt = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( a < b )\n" "return;\n" "doassert( a + \" is not less than \" + b + \" : \" + msg );\n" "}\n" "\n" "assert.gt = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( a > b )\n" "return;\n" "doassert( a + \" is not greater than \" + b + \" : \" + msg );\n" "}\n" "\n" "assert.lte = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( a <= b )\n" "return;\n" "doassert( a + \" is not less than or eq \" + b + \" : \" + msg );\n" "}\n" "\n" "assert.gte = function( a , b , msg ){\n" "if ( assert._debug && msg ) print( \"in assert for: \" + msg );\n" "\n" "if ( a >= b )\n" "return;\n" "doassert( a + \" is not greater than or eq \" + b + \" : \" + msg );\n" "}\n" "\n" "\n" "assert.close = function( a , b , msg , places ){\n" "if (places === undefined) {\n" "places = 4;\n" "}\n" "if (Math.round((a - b) * Math.pow(10, places)) === 0) {\n" "return;\n" "}\n" "doassert( a + \" is not equal to \" + b + \" within \" + places +\n" "\" places, diff: \" + (a-b) + \" : \" + msg );\n" "};\n" "\n" "Object.extend = function( dst , src , deep ){\n" "for ( var k in src ){\n" "var v = src[k];\n" "if ( deep && typeof(v) == \"object\" ){\n" "if ( \"floatApprox\" in v ) { // convert NumberLong properly\n" "eval( \"v = \" + tojson( v ) );\n" "} else {\n" "v = Object.extend( typeof ( v.length ) == \"number\" ? [] : {} , v , true );\n" "}\n" "}\n" "dst[k] = v;\n" "}\n" "return dst;\n" "}\n" "\n" "argumentsToArray = function( a ){\n" "var arr = [];\n" "for ( var i=0; i 0 ? '-' : '+'; // This is correct\n" "ofs += (ofsmin/60).zeroPad(2)\n" "ofs += (ofsmin%60).zeroPad(2)\n" "}\n" "}\n" "\n" "return 'ISODate(\"'+year+'-'+month+'-'+date+'T'+hour+':'+minute+':'+sec+ofs+'\")';\n" "}\n" "\n" "Date.printAsUTC = true;\n" "\n" "\n" "ISODate = function(isoDateStr){\n" "if (!isoDateStr)\n" "return new Date();\n" "\n" "var isoDateRegex = /(\\d{4})-?(\\d{2})-?(\\d{2})([T ](\\d{2})(:?(\\d{2})(:?(\\d{2}(\\.\\d+)?))?)?(Z|([+-])(\\d{2}):?(\\d{2})?)?)?/;\n" "var res = isoDateRegex.exec(isoDateStr);\n" "\n" "if (!res)\n" "throw \"invalid ISO date\";\n" "\n" "var year = parseInt(res[1],10) || 1970; // this should always be present\n" "var month = (parseInt(res[2],10) || 1) - 1;\n" "var date = parseInt(res[3],10) || 0;\n" "var hour = parseInt(res[5],10) || 0;\n" "var min = parseInt(res[7],10) || 0;\n" "var sec = parseFloat(res[9]) || 0;\n" "var ms = Math.round((sec%1) * 1000)\n" "sec -= ms/1000\n" "\n" "var time = Date.UTC(year, month, date, hour, min, sec, ms);\n" "\n" "if (res[11] && res[11] != 'Z'){\n" "var ofs = 0;\n" "ofs += (parseInt(res[13],10) || 0) * 60*60*1000; // hours\n" "ofs += (parseInt(res[14],10) || 0) * 60*1000; // mins\n" "if (res[12] == '+') // if ahead subtract\n" "ofs *= -1;\n" "\n" "time += ofs\n" "}\n" "\n" "return new Date(time);\n" "}\n" "\n" "RegExp.prototype.tojson = RegExp.prototype.toString;\n" "\n" "Array.contains = function( a , x ){\n" "for ( var i=0; i>>>>>>>>>>>>>> skipping \" + x.name);\n" "return;\n" "}\n" "\n" "params[ i % n ].push( x.name );\n" "++i;\n" "}\n" ");\n" "\n" "// randomize ordering of the serialTests\n" "params[ 0 ] = Array.shuffle( params[ 0 ] );\n" "\n" "for( var i in params ) {\n" "params[ i ].unshift( i );\n" "}\n" "\n" "return params;\n" "}\n" "\n" "// runs a set of test files\n" "// first argument is an identifier for this tester, remaining arguments are file names\n" "ParallelTester.fileTester = function() {\n" "var args = argumentsToArray( arguments );\n" "var suite = args.shift();\n" "args.forEach(\n" "function( x ) {\n" "print(\" S\" + suite + \" Test : \" + x + \" ...\");\n" "var time = Date.timeFunc( function() { load(x); }, 1);\n" "print(\" S\" + suite + \" Test : \" + x + \" \" + time + \"ms\" );\n" "}\n" ");\n" "}\n" "\n" "// params: array of arrays, each element of which consists of a function followed\n" "// by zero or more arguments to that function. Each function and its arguments will\n" "// be called in a separate thread.\n" "// msg: failure message\n" "// newScopes: if true, each thread starts in a fresh scope\n" "assert.parallelTests = function( params, msg, newScopes ) {\n" "newScopes = newScopes || false;\n" "var wrapper = function( fun, argv ) {\n" "eval (\n" "\"var z = function() {\" +\n" "\"var __parallelTests__fun = \" + fun.toString() + \";\" +\n" "\"var __parallelTests__argv = \" + tojson( argv ) + \";\" +\n" "\"var __parallelTests__passed = false;\" +\n" "\"try {\" +\n" "\"__parallelTests__fun.apply( 0, __parallelTests__argv );\" +\n" "\"__parallelTests__passed = true;\" +\n" "\"} catch ( e ) {\" +\n" "\"print( e );\" +\n" "\"}\" +\n" "\"return __parallelTests__passed;\" +\n" "\"}\"\n" ");\n" "return z;\n" "}\n" "var runners = new Array();\n" "for( var i in params ) {\n" "var param = params[ i ];\n" "var test = param.shift();\n" "var t;\n" "if ( newScopes )\n" "t = new ScopedThread( wrapper( test, param ) );\n" "else\n" "t = new Thread( wrapper( test, param ) );\n" "runners.push( t );\n" "}\n" "\n" "runners.forEach( function( x ) { x.start(); } );\n" "var nFailed = 0;\n" "// v8 doesn't like it if we exit before all threads are joined (SERVER-529)\n" "runners.forEach( function( x ) { if( !x.returnData() ) { ++nFailed; } } );\n" "assert.eq( 0, nFailed, msg );\n" "}\n" "}\n" "\n" "tojsononeline = function( x ){\n" "return tojson( x , \" \" , true );\n" "}\n" "\n" "tojson = function( x, indent , nolint ){\n" "if ( x === null )\n" "return \"null\";\n" "\n" "if ( x === undefined )\n" "return \"undefined\";\n" "\n" "if (!indent)\n" "indent = \"\";\n" "\n" "switch ( typeof x ) {\n" "case \"string\": {\n" "var s = \"\\\"\";\n" "for ( var i=0; i 1) {\n" "print(n + \"\\t\" + size[n] / 1024 / 1024 / 1024 + \"GB\");\n" "} else {\n" "print(n + \"\\t(empty)\");\n" "}\n" "});\n" "//db.getMongo().getDBNames().sort().forEach(function (x) { print(x) });\n" "return \"\";\n" "}\n" "\n" "throw \"don't know how to show [\" + what + \"]\";\n" "\n" "}\n" "\n" "if ( typeof( Map ) == \"undefined\" ){\n" "Map = function(){\n" "this._data = {};\n" "}\n" "}\n" "\n" "Map.hash = function( val ){\n" "if ( ! val )\n" "return val;\n" "\n" "switch ( typeof( val ) ){\n" "case 'string':\n" "case 'number':\n" "case 'date':\n" "return val.toString();\n" "case 'object':\n" "case 'array':\n" "var s = \"\";\n" "for ( var k in val ){\n" "s += k + val[k];\n" "}\n" "return s;\n" "}\n" "\n" "throw \"can't hash : \" + typeof( val );\n" "}\n" "\n" "Map.prototype.put = function( key , value ){\n" "var o = this._get( key );\n" "var old = o.value;\n" "o.value = value;\n" "return old;\n" "}\n" "\n" "Map.prototype.get = function( key ){\n" "return this._get( key ).value;\n" "}\n" "\n" "Map.prototype._get = function( key ){\n" "var h = Map.hash( key );\n" "var a = this._data[h];\n" "if ( ! a ){\n" "a = [];\n" "this._data[h] = a;\n" "}\n" "\n" "for ( var i=0; i= 1 || cross_prod <= -1){\n" "// fun with floats\n" "assert( Math.abs(cross_prod)-1 < 1e-6 );\n" "return cross_prod > 0 ? 0 : Math.PI;\n" "}\n" "\n" "return Math.acos(cross_prod);\n" "}\n" "\n" "rs = function () { return \"try rs.help()\"; }\n" "\n" "rs.help = function () {\n" "print(\"\\trs.status() { replSetGetStatus : 1 } checks repl set status\");\n" "print(\"\\trs.initiate() { replSetInitiate : null } initiates set with default settings\");\n" "print(\"\\trs.initiate(cfg) { replSetInitiate : cfg } initiates set with configuration cfg\");\n" "print(\"\\trs.conf() get the current configuration object from local.system.replset\");\n" "print(\"\\trs.reconfig(cfg) updates the configuration of a running replica set with cfg (disconnects)\");\n" "print(\"\\trs.add(hostportstr) add a new member to the set with default attributes (disconnects)\");\n" "print(\"\\trs.add(membercfgobj) add a new member to the set with extra attributes (disconnects)\");\n" "print(\"\\trs.addArb(hostportstr) add a new member which is arbiterOnly:true (disconnects)\");\n" "print(\"\\trs.stepDown([secs]) step down as primary (momentarily) (disconnects)\");\n" "print(\"\\trs.freeze(secs) make a node ineligible to become primary for the time specified\");\n" "print(\"\\trs.remove(hostportstr) remove a host from the replica set (disconnects)\");\n" "print(\"\\trs.slaveOk() shorthand for db.getMongo().setSlaveOk()\");\n" "print();\n" "print(\"\\tdb.isMaster() check who is primary\");\n" "print();\n" "print(\"\\treconfiguration helpers disconnect from the database so the shell will display\");\n" "print(\"\\tan error, even if the command succeeds.\");\n" "print(\"\\tsee also http://:28017/_replSet for additional diagnostic info\");\n" "}\n" "rs.slaveOk = function () { return db.getMongo().setSlaveOk(); }\n" "rs.status = function () { return db._adminCommand(\"replSetGetStatus\"); }\n" "rs.isMaster = function () { return db.isMaster(); }\n" "rs.initiate = function (c) { return db._adminCommand({ replSetInitiate: c }); }\n" "rs.reconfig = function (cfg) {\n" "cfg.version = rs.conf().version + 1;\n" "var res = null;\n" "try {\n" "res = db.adminCommand({ replSetReconfig: cfg });\n" "}\n" "catch (e) {\n" "print(\"shell got exception during reconfig: \" + e);\n" "print(\"in some circumstances, the primary steps down and closes connections on a reconfig\");\n" "}\n" "return res;\n" "}\n" "rs.add = function (hostport, arb) {\n" "var cfg = hostport;\n" "\n" "var local = db.getSisterDB(\"local\");\n" "assert(local.system.replset.count() <= 1, \"error: local.system.replset has unexpected contents\");\n" "var c = local.system.replset.findOne();\n" "assert(c, \"no config object retrievable from local.system.replset\");\n" "\n" "c.version++;\n" "\n" "var max = 0;\n" "for (var i in c.members)\n" "if (c.members[i]._id > max) max = c.members[i]._id;\n" "if (isString(hostport)) {\n" "cfg = { _id: max + 1, host: hostport };\n" "if (arb)\n" "cfg.arbiterOnly = true;\n" "}\n" "c.members.push(cfg);\n" "var res = null;\n" "try {\n" "res = db.adminCommand({ replSetReconfig: c });\n" "}\n" "catch (e) {\n" "print(\"shell got exception during reconfig: \" + e);\n" "print(\"in some circumstances, the primary steps down and closes connections on a reconfig\");\n" "}\n" "return res;\n" "}\n" "rs.stepDown = function (secs) { return db._adminCommand({ replSetStepDown:secs||60}); }\n" "rs.freeze = function (secs) { return db._adminCommand({replSetFreeze:secs}); }\n" "rs.addArb = function (hn) { return this.add(hn, true); }\n" "rs.conf = function () { return db.getSisterDB(\"local\").system.replset.findOne(); }\n" "\n" "rs.remove = function (hn) {\n" "var local = db.getSisterDB(\"local\");\n" "assert(local.system.replset.count() <= 1, \"error: local.system.replset has unexpected contents\");\n" "var c = local.system.replset.findOne();\n" "assert(c, \"no config object retrievable from local.system.replset\");\n" "c.version++;\n" "\n" "for (var i in c.members) {\n" "if (c.members[i].host == hn) {\n" "c.members.splice(i, 1);\n" "return db._adminCommand({ replSetReconfig : c});\n" "}\n" "}\n" "\n" "return \"error: couldn't find \"+hn+\" in \"+tojson(c.members);\n" "};\n" "\n" "help = shellHelper.help = function (x) {\n" "if (x == \"mr\") {\n" "print(\"\\nSee also http://www.mongodb.org/display/DOCS/MapReduce\");\n" "print(\"\\nfunction mapf() {\");\n" "print(\" // 'this' holds current document to inspect\");\n" "print(\" emit(key, value);\");\n" "print(\"}\");\n" "print(\"\\nfunction reducef(key,value_array) {\");\n" "print(\" return reduced_value;\");\n" "print(\"}\");\n" "print(\"\\ndb.mycollection.mapReduce(mapf, reducef[, options])\");\n" "print(\"\\noptions\");\n" "print(\"{[query : ]\");\n" "print(\" [, sort : ]\");\n" "print(\" [, limit : ]\");\n" "print(\" [, out : ]\");\n" "print(\" [, keeptemp: ]\");\n" "print(\" [, finalize : ]\");\n" "print(\" [, scope : ]\");\n" "print(\" [, verbose : true]}\\n\");\n" "return;\n" "} else if (x == \"connect\") {\n" "print(\"\\nNormally one specifies the server on the mongo shell command line. Run mongo --help to see those options.\");\n" "print(\"Additional connections may be opened:\\n\");\n" "print(\" var x = new Mongo('host[:port]');\");\n" "print(\" var mydb = x.getDB('mydb');\");\n" "print(\" or\");\n" "print(\" var mydb = connect('host[:port]/mydb');\");\n" "print(\"\\nNote: the REPL prompt only auto-reports getLastError() for the shell command line connection.\\n\");\n" "return;\n" "}\n" "else if (x == \"misc\") {\n" "print(\"\\tb = new BinData(subtype,base64str) create a BSON BinData value\");\n" "print(\"\\tb.subtype() the BinData subtype (0..255)\");\n" "print(\"\\tb.length() length of the BinData data in bytes\");\n" "print(\"\\tb.hex() the data as a hex encoded string\");\n" "print(\"\\tb.base64() the data as a base 64 encoded string\");\n" "print(\"\\tb.toString()\");\n" "print();\n" "print(\"\\to = new ObjectId() create a new ObjectId\");\n" "print(\"\\to.getTimestamp() return timestamp derived from first 32 bits of the OID\");\n" "print(\"\\to.isObjectId()\");\n" "print(\"\\to.toString()\");\n" "print(\"\\to.equals(otherid)\");\n" "return;\n" "}\n" "else if (x == \"admin\") {\n" "print(\"\\tls([path]) list files\");\n" "print(\"\\tpwd() returns current directory\");\n" "print(\"\\tlistFiles([path]) returns file list\");\n" "print(\"\\thostname() returns name of this host\");\n" "print(\"\\tcat(fname) returns contents of text file as a string\");\n" "print(\"\\tremoveFile(f) delete a file or directory\");\n" "print(\"\\tload(jsfilename) load and execute a .js file\");\n" "print(\"\\trun(program[, args...]) spawn a program and wait for its completion\");\n" "print(\"\\trunProgram(program[, args...]) same as run(), above\");\n" "print(\"\\tsleep(m) sleep m milliseconds\");\n" "print(\"\\tgetMemInfo() diagnostic\");\n" "return;\n" "}\n" "else if (x == \"test\") {\n" "print(\"\\tstartMongodEmpty(args) DELETES DATA DIR and then starts mongod\");\n" "print(\"\\t returns a connection to the new server\");\n" "print(\"\\tstartMongodTest(port,dir,options)\");\n" "print(\"\\t DELETES DATA DIR\");\n" "print(\"\\t automatically picks port #s starting at 27000 and increasing\");\n" "print(\"\\t or you can specify the port as the first arg\");\n" "print(\"\\t dir is /data/db// if not specified as the 2nd arg\");\n" "print(\"\\t returns a connection to the new server\");\n" "print(\"\\tresetDbpath(dirpathstr) deletes everything under the dir specified including subdirs\");\n" "print(\"\\tstopMongoProgram(port[, signal])\");\n" "return;\n" "}\n" "else if (x == \"\") {\n" "print(\"\\t\" + \"db.help() help on db methods\");\n" "print(\"\\t\" + \"db.mycoll.help() help on collection methods\");\n" "print(\"\\t\" + \"rs.help() help on replica set methods\");\n" "print(\"\\t\" + \"help connect connecting to a db help\");\n" "print(\"\\t\" + \"help admin administrative help\");\n" "print(\"\\t\" + \"help misc misc things to know\");\n" "print(\"\\t\" + \"help mr mapreduce help\");\n" "print();\n" "print(\"\\t\" + \"show dbs show database names\");\n" "print(\"\\t\" + \"show collections show collections in current database\");\n" "print(\"\\t\" + \"show users show users in current database\");\n" "print(\"\\t\" + \"show profile show most recent system.profile entries with time >= 1ms\");\n" "print(\"\\t\" + \"use set current database\");\n" "print(\"\\t\" + \"db.foo.find() list objects in collection foo\");\n" "print(\"\\t\" + \"db.foo.find( { a : 1 } ) list objects in foo where a == 1\");\n" "print(\"\\t\" + \"it result of the last line evaluated; use to further iterate\");\n" "print(\"\\t\" + \"DBQuery.shellBatchSize = x set default number of items to display on shell\");\n" "print(\"\\t\" + \"exit quit the mongo shell\");\n" "}\n" "else\n" "print(\"unknown help option\");\n" "}\n" ; extern const JSFile utils; const JSFile utils = { "shell/utils.js" , _jscode_raw_utils }; const StringData _jscode_raw_db = "// db.js\n" "\n" "if ( typeof DB == \"undefined\" ){\n" "DB = function( mongo , name ){\n" "this._mongo = mongo;\n" "this._name = name;\n" "}\n" "}\n" "\n" "DB.prototype.getMongo = function(){\n" "assert( this._mongo , \"why no mongo!\" );\n" "return this._mongo;\n" "}\n" "\n" "DB.prototype.getSiblingDB = function( name ){\n" "return this.getMongo().getDB( name );\n" "}\n" "\n" "DB.prototype.getSisterDB = DB.prototype.getSiblingDB;\n" "\n" "DB.prototype.getName = function(){\n" "return this._name;\n" "}\n" "\n" "DB.prototype.stats = function(){\n" "return this.runCommand( { dbstats : 1 } );\n" "}\n" "\n" "DB.prototype.getCollection = function( name ){\n" "return new DBCollection( this._mongo , this , name , this._name + \".\" + name );\n" "}\n" "\n" "DB.prototype.commandHelp = function( name ){\n" "var c = {};\n" "c[name] = 1;\n" "c.help = true;\n" "return this.runCommand( c ).help;\n" "}\n" "\n" "DB.prototype.runCommand = function( obj ){\n" "if ( typeof( obj ) == \"string\" ){\n" "var n = {};\n" "n[obj] = 1;\n" "obj = n;\n" "}\n" "return this.getCollection( \"$cmd\" ).findOne( obj );\n" "}\n" "\n" "DB.prototype._dbCommand = DB.prototype.runCommand;\n" "\n" "DB.prototype.adminCommand = function( obj ){\n" "if ( this._name == \"admin\" )\n" "return this.runCommand( obj );\n" "return this.getSiblingDB( \"admin\" ).runCommand( obj );\n" "}\n" "\n" "DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name\n" "\n" "DB.prototype.addUser = function( username , pass, readOnly ){\n" "readOnly = readOnly || false;\n" "var c = this.getCollection( \"system.users\" );\n" "\n" "var u = c.findOne( { user : username } ) || { user : username };\n" "u.readOnly = readOnly;\n" "u.pwd = hex_md5( username + \":mongo:\" + pass );\n" "print( tojson( u ) );\n" "\n" "c.save( u );\n" "}\n" "\n" "DB.prototype.removeUser = function( username ){\n" "this.getCollection( \"system.users\" ).remove( { user : username } );\n" "}\n" "\n" "DB.prototype.__pwHash = function( nonce, username, pass ) {\n" "return hex_md5( nonce + username + hex_md5( username + \":mongo:\" + pass ) );\n" "}\n" "\n" "DB.prototype.auth = function( username , pass ){\n" "var n = this.runCommand( { getnonce : 1 } );\n" "\n" "var a = this.runCommand(\n" "{\n" "authenticate : 1 ,\n" "user : username ,\n" "nonce : n.nonce ,\n" "key : this.__pwHash( n.nonce, username, pass )\n" "}\n" ");\n" "\n" "return a.ok;\n" "}\n" "\n" "/**\n" "Create a new collection in the database. Normally, collection creation is automatic. You would\n" "use this function if you wish to specify special options on creation.\n" "\n" "If the collection already exists, no action occurs.\n" "\n" "

Options:

\n" "
    \n" "
  • \n" "size: desired initial extent size for the collection. Must be <= 1000000000.\n" "for fixed size (capped) collections, this size is the total/max size of the\n" "collection.\n" "
  • \n" "
  • \n" "capped: if true, this is a capped collection (where old data rolls out).\n" "
  • \n" "
  • max: maximum number of objects if capped (optional).
  • \n" "
\n" "\n" "

Example:

\n" "\n" "db.createCollection(\"movies\", { size: 10 * 1024 * 1024, capped:true } );\n" "\n" "* @param {String} name Name of new collection to create\n" "* @param {Object} options Object with options for call. Options are listed above.\n" "* @return SOMETHING_FIXME\n" "*/\n" "DB.prototype.createCollection = function(name, opt) {\n" "var options = opt || {};\n" "var cmd = { create: name, capped: options.capped, size: options.size, max: options.max };\n" "var res = this._dbCommand(cmd);\n" "return res;\n" "}\n" "\n" "/**\n" "* @deprecated use getProfilingStatus\n" "* Returns the current profiling level of this database\n" "* @return SOMETHING_FIXME or null on error\n" "*/\n" "DB.prototype.getProfilingLevel = function() {\n" "var res = this._dbCommand( { profile: -1 } );\n" "return res ? res.was : null;\n" "}\n" "\n" "/**\n" "* @return the current profiling status\n" "* example { was : 0, slowms : 100 }\n" "* @return SOMETHING_FIXME or null on error\n" "*/\n" "DB.prototype.getProfilingStatus = function() {\n" "var res = this._dbCommand( { profile: -1 } );\n" "if ( ! res.ok )\n" "throw \"profile command failed: \" + tojson( res );\n" "delete res.ok\n" "return res;\n" "}\n" "\n" "\n" "/**\n" "Erase the entire database. (!)\n" "\n" "* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n" "*/\n" "DB.prototype.dropDatabase = function() {\n" "if ( arguments.length )\n" "throw \"dropDatabase doesn't take arguments\";\n" "return this._dbCommand( { dropDatabase: 1 } );\n" "}\n" "\n" "\n" "DB.prototype.shutdownServer = function() {\n" "if( \"admin\" != this._name ){\n" "return \"shutdown command only works with the admin database; try 'use admin'\";\n" "}\n" "\n" "try {\n" "var res = this._dbCommand(\"shutdown\");\n" "if( res )\n" "throw \"shutdownServer failed: \" + res.errmsg;\n" "throw \"shutdownServer failed\";\n" "}\n" "catch ( e ){\n" "assert( tojson( e ).indexOf( \"error doing query: failed\" ) >= 0 , \"unexpected error: \" + tojson( e ) );\n" "print( \"server should be down...\" );\n" "}\n" "}\n" "\n" "/**\n" "Clone database on another server to here.\n" "

\n" "Generally, you should dropDatabase() first as otherwise the cloned information will MERGE\n" "into whatever data is already present in this database. (That is however a valid way to use\n" "clone if you are trying to do something intentionally, such as union three non-overlapping\n" "databases into one.)\n" "

\n" "This is a low level administrative function will is not typically used.\n" "\n" "* @param {String} from Where to clone from (dbhostname[:port]). May not be this database\n" "(self) as you cannot clone to yourself.\n" "* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n" "* See also: db.copyDatabase()\n" "*/\n" "DB.prototype.cloneDatabase = function(from) {\n" "assert( isString(from) && from.length );\n" "//this.resetIndexCache();\n" "return this._dbCommand( { clone: from } );\n" "}\n" "\n" "\n" "/**\n" "Clone collection on another server to here.\n" "

\n" "Generally, you should drop() first as otherwise the cloned information will MERGE\n" "into whatever data is already present in this collection. (That is however a valid way to use\n" "clone if you are trying to do something intentionally, such as union three non-overlapping\n" "collections into one.)\n" "

\n" "This is a low level administrative function is not typically used.\n" "\n" "* @param {String} from mongod instance from which to clnoe (dbhostname:port). May\n" "not be this mongod instance, as clone from self is not allowed.\n" "* @param {String} collection name of collection to clone.\n" "* @param {Object} query query specifying which elements of collection are to be cloned.\n" "* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n" "* See also: db.cloneDatabase()\n" "*/\n" "DB.prototype.cloneCollection = function(from, collection, query) {\n" "assert( isString(from) && from.length );\n" "assert( isString(collection) && collection.length );\n" "collection = this._name + \".\" + collection;\n" "query = query || {};\n" "//this.resetIndexCache();\n" "return this._dbCommand( { cloneCollection:collection, from:from, query:query } );\n" "}\n" "\n" "\n" "/**\n" "Copy database from one server or name to another server or name.\n" "\n" "Generally, you should dropDatabase() first as otherwise the copied information will MERGE\n" "into whatever data is already present in this database (and you will get duplicate objects\n" "in collections potentially.)\n" "\n" "For security reasons this function only works when executed on the \"admin\" db. However,\n" "if you have access to said db, you can copy any database from one place to another.\n" "\n" "This method provides a way to \"rename\" a database by copying it to a new db name and\n" "location. Additionally, it effectively provides a repair facility.\n" "\n" "* @param {String} fromdb database name from which to copy.\n" "* @param {String} todb database name to copy to.\n" "* @param {String} fromhost hostname of the database (and optionally, \":port\") from which to\n" "copy the data. default if unspecified is to copy from self.\n" "* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n" "* See also: db.clone()\n" "*/\n" "DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password) {\n" "assert( isString(fromdb) && fromdb.length );\n" "assert( isString(todb) && todb.length );\n" "fromhost = fromhost || \"\";\n" "if ( username && password ) {\n" "var n = this._adminCommand( { copydbgetnonce : 1, fromhost:fromhost } );\n" "return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb, username:username, nonce:n.nonce, key:this.__pwHash( n.nonce, username, password ) } );\n" "} else {\n" "return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb } );\n" "}\n" "}\n" "\n" "/**\n" "Repair database.\n" "\n" "* @return Object returned has member ok set to true if operation succeeds, false otherwise.\n" "*/\n" "DB.prototype.repairDatabase = function() {\n" "return this._dbCommand( { repairDatabase: 1 } );\n" "}\n" "\n" "\n" "DB.prototype.help = function() {\n" "print(\"DB methods:\");\n" "print(\"\\tdb.addUser(username, password[, readOnly=false])\");\n" "print(\"\\tdb.auth(username, password)\");\n" "print(\"\\tdb.cloneDatabase(fromhost)\");\n" "print(\"\\tdb.commandHelp(name) returns the help for the command\");\n" "print(\"\\tdb.copyDatabase(fromdb, todb, fromhost)\");\n" "print(\"\\tdb.createCollection(name, { size : ..., capped : ..., max : ... } )\");\n" "print(\"\\tdb.currentOp() displays the current operation in the db\");\n" "print(\"\\tdb.dropDatabase()\");\n" "print(\"\\tdb.eval(func, args) run code server-side\");\n" "print(\"\\tdb.getCollection(cname) same as db['cname'] or db.cname\");\n" "print(\"\\tdb.getCollectionNames()\");\n" "print(\"\\tdb.getLastError() - just returns the err msg string\");\n" "print(\"\\tdb.getLastErrorObj() - return full status object\");\n" "print(\"\\tdb.getMongo() get the server connection object\");\n" "print(\"\\tdb.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair\");\n" "print(\"\\tdb.getName()\");\n" "print(\"\\tdb.getPrevError()\");\n" "print(\"\\tdb.getProfilingLevel() - deprecated\");\n" "print(\"\\tdb.getProfilingStatus() - returns if profiling is on and slow threshold \");\n" "print(\"\\tdb.getReplicationInfo()\");\n" "print(\"\\tdb.getSiblingDB(name) get the db at the same server as this one\");\n" "print(\"\\tdb.isMaster() check replica primary status\");\n" "print(\"\\tdb.killOp(opid) kills the current operation in the db\");\n" "print(\"\\tdb.listCommands() lists all the db commands\");\n" "print(\"\\tdb.printCollectionStats()\");\n" "print(\"\\tdb.printReplicationInfo()\");\n" "print(\"\\tdb.printSlaveReplicationInfo()\");\n" "print(\"\\tdb.printShardingStatus()\");\n" "print(\"\\tdb.removeUser(username)\");\n" "print(\"\\tdb.repairDatabase()\");\n" "print(\"\\tdb.resetError()\");\n" "print(\"\\tdb.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }\");\n" "print(\"\\tdb.serverStatus()\");\n" "print(\"\\tdb.setProfilingLevel(level,) 0=off 1=slow 2=all\");\n" "print(\"\\tdb.shutdownServer()\");\n" "print(\"\\tdb.stats()\");\n" "print(\"\\tdb.version() current version of the server\");\n" "print(\"\\tdb.getMongo().setSlaveOk() allow queries on a replication slave server\");\n" "\n" "return __magicNoPrint;\n" "}\n" "\n" "DB.prototype.printCollectionStats = function(){\n" "var mydb = this;\n" "this.getCollectionNames().forEach(\n" "function(z){\n" "print( z );\n" "printjson( mydb.getCollection(z).stats() );\n" "print( \"---\" );\n" "}\n" ");\n" "}\n" "\n" "/**\n" "*

Set profiling level for your db. Profiling gathers stats on query performance.

\n" "*\n" "*

Default is off, and resets to off on a database restart -- so if you want it on,\n" "* turn it on periodically.

\n" "*\n" "*

Levels :

\n" "*
    \n" "*
  • 0=off
  • \n" "*
  • 1=log very slow operations; optional argument slowms specifies slowness threshold
  • \n" "*
  • 2=log all
  • \n" "* @param {String} level Desired level of profiling\n" "* @param {String} slowms For slow logging, query duration that counts as slow (default 100ms)\n" "* @return SOMETHING_FIXME or null on error\n" "*/\n" "DB.prototype.setProfilingLevel = function(level,slowms) {\n" "\n" "if (level < 0 || level > 2) {\n" "throw { dbSetProfilingException : \"input level \" + level + \" is out of range [0..2]\" };\n" "}\n" "\n" "var cmd = { profile: level };\n" "if ( slowms )\n" "cmd[\"slowms\"] = slowms;\n" "return this._dbCommand( cmd );\n" "}\n" "\n" "\n" "/**\n" "*

    Evaluate a js expression at the database server.

    \n" "*\n" "*

    Useful if you need to touch a lot of data lightly; in such a scenario\n" "* the network transfer of the data could be a bottleneck. A good example\n" "* is \"select count(*)\" -- can be done server side via this mechanism.\n" "*

    \n" "*\n" "*

    \n" "* If the eval fails, an exception is thrown of the form:\n" "*

    \n" "* { dbEvalException: { retval: functionReturnValue, ok: num [, errno: num] [, errmsg: str] } }\n" "*\n" "*

    Example:

    \n" "* print( \"mycount: \" + db.eval( function(){db.mycoll.find({},{_id:ObjId()}).length();} );\n" "*\n" "* @param {Function} jsfunction Javascript function to run on server. Note this it not a closure, but rather just \"code\".\n" "* @return result of your function, or null if error\n" "*\n" "*/\n" "DB.prototype.eval = function(jsfunction) {\n" "var cmd = { $eval : jsfunction };\n" "if ( arguments.length > 1 ) {\n" "cmd.args = argumentsToArray( arguments ).slice(1);\n" "}\n" "\n" "var res = this._dbCommand( cmd );\n" "\n" "if (!res.ok)\n" "throw tojson( res );\n" "\n" "return res.retval;\n" "}\n" "\n" "DB.prototype.dbEval = DB.prototype.eval;\n" "\n" "\n" "/**\n" "*\n" "*

    \n" "* Similar to SQL group by. For example:

    \n" "*\n" "* select a,b,sum(c) csum from coll where active=1 group by a,b\n" "*\n" "*

    \n" "* corresponds to the following in 10gen:\n" "*

    \n" "*\n" "* \n" "db.group(\n" "{\n" "ns: \"coll\",\n" "key: { a:true, b:true },\n" "// keyf: ...,\n" "cond: { active:1 },\n" "reduce: function(obj,prev) { prev.csum += obj.c; } ,\n" "initial: { csum: 0 }\n" "});\n" "\n" "*\n" "*\n" "*

    \n" "* An array of grouped items is returned. The array must fit in RAM, thus this function is not\n" "* suitable when the return set is extremely large.\n" "*

    \n" "*

    \n" "* To order the grouped data, simply sort it client side upon return.\n" "*

    \n" "Defaults\n" "cond may be null if you want to run against all rows in the collection\n" "keyf is a function which takes an object and returns the desired key. set either key or keyf (not both).\n" "*

    \n" "*/\n" "DB.prototype.groupeval = function(parmsObj) {\n" "\n" "var groupFunction = function() {\n" "var parms = args[0];\n" "var c = db[parms.ns].find(parms.cond||{});\n" "var map = new Map();\n" "var pks = parms.key ? Object.keySet( parms.key ) : null;\n" "var pkl = pks ? pks.length : 0;\n" "var key = {};\n" "\n" "while( c.hasNext() ) {\n" "var obj = c.next();\n" "if ( pks ) {\n" "for( var i=0; i, nPrev : , ok : 1 }\n" "\n" "result.err will be null if no error has occurred.\n" "*/\n" "DB.prototype.getPrevError = function(){\n" "return this.runCommand( { getpreverror : 1 } );\n" "}\n" "\n" "DB.prototype.getCollectionNames = function(){\n" "var all = [];\n" "\n" "var nsLength = this._name.length + 1;\n" "\n" "var c = this.getCollection( \"system.namespaces\" ).find();\n" "while ( c.hasNext() ){\n" "var name = c.next().name;\n" "\n" "if ( name.indexOf( \"$\" ) >= 0 && name.indexOf( \".oplog.$\" ) < 0 )\n" "continue;\n" "\n" "all.push( name.substring( nsLength ) );\n" "}\n" "\n" "return all.sort();\n" "}\n" "\n" "DB.prototype.tojson = function(){\n" "return this._name;\n" "}\n" "\n" "DB.prototype.toString = function(){\n" "return this._name;\n" "}\n" "\n" "DB.prototype.isMaster = function () { return this.runCommand(\"isMaster\"); }\n" "\n" "DB.prototype.currentOp = function(){\n" "return db.$cmd.sys.inprog.findOne();\n" "}\n" "DB.prototype.currentOP = DB.prototype.currentOp;\n" "\n" "DB.prototype.killOp = function(op) {\n" "if( !op )\n" "throw \"no opNum to kill specified\";\n" "return db.$cmd.sys.killop.findOne({'op':op});\n" "}\n" "DB.prototype.killOP = DB.prototype.killOp;\n" "\n" "DB.tsToSeconds = function(x){\n" "if ( x.t && x.i )\n" "return x.t / 1000;\n" "return x / 4294967296; // low 32 bits are ordinal #s within a second\n" "}\n" "\n" "/**\n" "Get a replication log information summary.\n" "

    \n" "This command is for the database/cloud administer and not applicable to most databases.\n" "It is only used with the local database. One might invoke from the JS shell:\n" "

    \n" 
    "use local\n" 
    "db.getReplicationInfo();\n" 
    "
    \n" "It is assumed that this database is a replication master -- the information returned is\n" "about the operation log stored at local.oplog.$main on the replication master. (It also\n" "works on a machine in a replica pair: for replica pairs, both machines are \"masters\" from\n" "an internal database perspective.\n" "

    \n" "* @return Object timeSpan: time span of the oplog from start to end if slave is more out\n" "* of date than that, it can't recover without a complete resync\n" "*/\n" "DB.prototype.getReplicationInfo = function() {\n" "var db = this.getSiblingDB(\"local\");\n" "\n" "var result = { };\n" "var oplog;\n" "if (db.system.namespaces.findOne({name:\"local.oplog.rs\"}) != null) {\n" "oplog = 'oplog.rs';\n" "}\n" "else if (db.system.namespaces.findOne({name:\"local.oplog.$main\"}) != null) {\n" "oplog = 'oplog.$main';\n" "}\n" "else {\n" "result.errmsg = \"neither master/slave nor replica set replication detected\";\n" "return result;\n" "}\n" "\n" "var ol_entry = db.system.namespaces.findOne({name:\"local.\"+oplog});\n" "if( ol_entry && ol_entry.options ) {\n" "result.logSizeMB = ol_entry.options.size / ( 1024 * 1024 );\n" "} else {\n" "result.errmsg = \"local.\"+oplog+\", or its options, not found in system.namespaces collection\";\n" "return result;\n" "}\n" "ol = db.getCollection(oplog);\n" "\n" "result.usedMB = ol.stats().size / ( 1024 * 1024 );\n" "result.usedMB = Math.ceil( result.usedMB * 100 ) / 100;\n" "\n" "var firstc = ol.find().sort({$natural:1}).limit(1);\n" "var lastc = ol.find().sort({$natural:-1}).limit(1);\n" "if( !firstc.hasNext() || !lastc.hasNext() ) {\n" "result.errmsg = \"objects not found in local.oplog.$main -- is this a new and empty db instance?\";\n" "result.oplogMainRowCount = ol.count();\n" "return result;\n" "}\n" "\n" "var first = firstc.next();\n" "var last = lastc.next();\n" "{\n" "var tfirst = first.ts;\n" "var tlast = last.ts;\n" "\n" "if( tfirst && tlast ) {\n" "tfirst = DB.tsToSeconds( tfirst );\n" "tlast = DB.tsToSeconds( tlast );\n" "result.timeDiff = tlast - tfirst;\n" "result.timeDiffHours = Math.round(result.timeDiff / 36)/100;\n" "result.tFirst = (new Date(tfirst*1000)).toString();\n" "result.tLast = (new Date(tlast*1000)).toString();\n" "result.now = Date();\n" "}\n" "else {\n" "result.errmsg = \"ts element not found in oplog objects\";\n" "}\n" "}\n" "\n" "return result;\n" "};\n" "\n" "DB.prototype.printReplicationInfo = function() {\n" "var result = this.getReplicationInfo();\n" "if( result.errmsg ) {\n" "print(tojson(result));\n" "return;\n" "}\n" "print(\"configured oplog size: \" + result.logSizeMB + \"MB\");\n" "print(\"log length start to end: \" + result.timeDiff + \"secs (\" + result.timeDiffHours + \"hrs)\");\n" "print(\"oplog first event time: \" + result.tFirst);\n" "print(\"oplog last event time: \" + result.tLast);\n" "print(\"now: \" + result.now);\n" "}\n" "\n" "DB.prototype.printSlaveReplicationInfo = function() {\n" "function getReplLag(st) {\n" "var now = new Date();\n" "print(\"\\t syncedTo: \" + st.toString() );\n" "var ago = (now-st)/1000;\n" "var hrs = Math.round(ago/36)/100;\n" "print(\"\\t\\t = \" + Math.round(ago) + \"secs ago (\" + hrs + \"hrs)\");\n" "};\n" "\n" "function g(x) {\n" "assert( x , \"how could this be null (printSlaveReplicationInfo gx)\" )\n" "print(\"source: \" + x.host);\n" "if ( x.syncedTo ){\n" "var st = new Date( DB.tsToSeconds( x.syncedTo ) * 1000 );\n" "getReplLag(st);\n" "}\n" "else {\n" "print( \"\\t doing initial sync\" );\n" "}\n" "};\n" "\n" "function r(x) {\n" "assert( x , \"how could this be null (printSlaveReplicationInfo rx)\" );\n" "if ( x.state == 1 ) {\n" "return;\n" "}\n" "\n" "print(\"source: \" + x.name);\n" "if ( x.optime ) {\n" "getReplLag(x.optimeDate);\n" "}\n" "else {\n" "print( \"\\t no replication info, yet. State: \" + x.stateStr );\n" "}\n" "};\n" "\n" "var L = this.getSiblingDB(\"local\");\n" "if( L.sources.count() != 0 ) {\n" "L.sources.find().forEach(g);\n" "}\n" "else if (L.system.replset.count() != 0) {\n" "var status = this.adminCommand({'replSetGetStatus' : 1});\n" "status.members.forEach(r);\n" "}\n" "else {\n" "print(\"local.sources is empty; is this db a --slave?\");\n" "return;\n" "}\n" "}\n" "\n" "DB.prototype.serverBuildInfo = function(){\n" "return this._adminCommand( \"buildinfo\" );\n" "}\n" "\n" "DB.prototype.serverStatus = function(){\n" "return this._adminCommand( \"serverStatus\" );\n" "}\n" "\n" "DB.prototype.serverCmdLineOpts = function(){\n" "return this._adminCommand( \"getCmdLineOpts\" );\n" "}\n" "\n" "DB.prototype.version = function(){\n" "return this.serverBuildInfo().version;\n" "}\n" "\n" "DB.prototype.serverBits = function(){\n" "return this.serverBuildInfo().bits;\n" "}\n" "\n" "DB.prototype.listCommands = function(){\n" "var x = this.runCommand( \"listCommands\" );\n" "for ( var name in x.commands ){\n" "var c = x.commands[name];\n" "\n" "var s = name + \": \";\n" "\n" "switch ( c.lockType ){\n" "case -1: s += \"read-lock\"; break;\n" "case 0: s += \"no-lock\"; break;\n" "case 1: s += \"write-lock\"; break;\n" "default: s += c.lockType;\n" "}\n" "\n" "if (c.adminOnly) s += \" adminOnly \";\n" "if (c.adminOnly) s += \" slaveOk \";\n" "\n" "s += \"\\n \";\n" "s += c.help.replace(/\\n/g, '\\n ');\n" "s += \"\\n\";\n" "\n" "print( s );\n" "}\n" "}\n" "\n" "DB.prototype.printShardingStatus = function(){\n" "printShardingStatus( this.getSiblingDB( \"config\" ) );\n" "}\n" "\n" "DB.autocomplete = function(obj){\n" "var colls = obj.getCollectionNames();\n" "var ret=[];\n" "for (var i=0; i 0 && this._cursorSeen >= this._limit )\n" "return false;\n" "var o = this._cursor.hasNext();\n" "return o;\n" "}\n" "\n" "DBQuery.prototype.next = function(){\n" "this._exec();\n" "\n" "var o = this._cursor.hasNext();\n" "if ( o )\n" "this._cursorSeen++;\n" "else\n" "throw \"error hasNext: \" + o;\n" "\n" "var ret = this._cursor.next();\n" "if ( ret.$err && this._numReturned == 0 && ! this.hasNext() )\n" "throw \"error: \" + tojson( ret );\n" "\n" "this._numReturned++;\n" "return ret;\n" "}\n" "\n" "DBQuery.prototype.objsLeftInBatch = function(){\n" "this._exec();\n" "\n" "var ret = this._cursor.objsLeftInBatch();\n" "if ( ret.$err )\n" "throw \"error: \" + tojson( ret );\n" "\n" "return ret;\n" "}\n" "\n" "DBQuery.prototype.toArray = function(){\n" "if ( this._arr )\n" "return this._arr;\n" "\n" "var a = [];\n" "while ( this.hasNext() )\n" "a.push( this.next() );\n" "this._arr = a;\n" "return a;\n" "}\n" "\n" "DBQuery.prototype.count = function( applySkipLimit ){\n" "var cmd = { count: this._collection.getName() };\n" "if ( this._query ){\n" "if ( this._special )\n" "cmd.query = this._query.query;\n" "else\n" "cmd.query = this._query;\n" "}\n" "cmd.fields = this._fields || {};\n" "\n" "if ( applySkipLimit ){\n" "if ( this._limit )\n" "cmd.limit = this._limit;\n" "if ( this._skip )\n" "cmd.skip = this._skip;\n" "}\n" "\n" "var res = this._db.runCommand( cmd );\n" "if( res && res.n != null ) return res.n;\n" "throw \"count failed: \" + tojson( res );\n" "}\n" "\n" "DBQuery.prototype.size = function(){\n" "return this.count( true );\n" "}\n" "\n" "DBQuery.prototype.countReturn = function(){\n" "var c = this.count();\n" "\n" "if ( this._skip )\n" "c = c - this._skip;\n" "\n" "if ( this._limit > 0 && this._limit < c )\n" "return this._limit;\n" "\n" "return c;\n" "}\n" "\n" "/**\n" "* iterative count - only for testing\n" "*/\n" "DBQuery.prototype.itcount = function(){\n" "var num = 0;\n" "while ( this.hasNext() ){\n" "num++;\n" "this.next();\n" "}\n" "return num;\n" "}\n" "\n" "DBQuery.prototype.length = function(){\n" "return this.toArray().length;\n" "}\n" "\n" "DBQuery.prototype._addSpecial = function( name , value ){\n" "this._ensureSpecial();\n" "this._query[name] = value;\n" "return this;\n" "}\n" "\n" "DBQuery.prototype.sort = function( sortBy ){\n" "return this._addSpecial( \"orderby\" , sortBy );\n" "}\n" "\n" "DBQuery.prototype.hint = function( hint ){\n" "return this._addSpecial( \"$hint\" , hint );\n" "}\n" "\n" "DBQuery.prototype.min = function( min ) {\n" "return this._addSpecial( \"$min\" , min );\n" "}\n" "\n" "DBQuery.prototype.max = function( max ) {\n" "return this._addSpecial( \"$max\" , max );\n" "}\n" "\n" "DBQuery.prototype.showDiskLoc = function() {\n" "return this._addSpecial( \"$showDiskLoc\" , true);\n" "}\n" "\n" "DBQuery.prototype.forEach = function( func ){\n" "while ( this.hasNext() )\n" "func( this.next() );\n" "}\n" "\n" "DBQuery.prototype.map = function( func ){\n" "var a = [];\n" "while ( this.hasNext() )\n" "a.push( func( this.next() ) );\n" "return a;\n" "}\n" "\n" "DBQuery.prototype.arrayAccess = function( idx ){\n" "return this.toArray()[idx];\n" "}\n" "\n" "DBQuery.prototype.explain = function (verbose) {\n" "/* verbose=true --> include allPlans, oldPlan fields */\n" "var n = this.clone();\n" "n._ensureSpecial();\n" "n._query.$explain = true;\n" "n._limit = Math.abs(n._limit) * -1;\n" "var e = n.next();\n" "\n" "function cleanup(obj){\n" "if (typeof(obj) != 'object'){\n" "return;\n" "}\n" "\n" "delete obj.allPlans;\n" "delete obj.oldPlan;\n" "\n" "if (typeof(obj.length) == 'number'){\n" "for (var i=0; i < obj.length; i++){\n" "cleanup(obj[i]);\n" "}\n" "}\n" "\n" "if (obj.shards){\n" "for (var key in obj.shards){\n" "cleanup(obj.shards[key]);\n" "}\n" "}\n" "\n" "if (obj.clauses){\n" "cleanup(obj.clauses);\n" "}\n" "}\n" "\n" "if (!verbose)\n" "cleanup(e);\n" "\n" "return e;\n" "}\n" "\n" "DBQuery.prototype.snapshot = function(){\n" "this._ensureSpecial();\n" "this._query.$snapshot = true;\n" "return this;\n" "}\n" "\n" "DBQuery.prototype.pretty = function(){\n" "this._prettyShell = true;\n" "return this;\n" "}\n" "\n" "DBQuery.prototype.shellPrint = function(){\n" "try {\n" "var n = 0;\n" "while ( this.hasNext() && n < DBQuery.shellBatchSize ){\n" "var s = this._prettyShell ? tojson( this.next() ) : tojson( this.next() , \"\" , true );\n" "print( s );\n" "n++;\n" "}\n" "if ( this.hasNext() ){\n" "print( \"has more\" );\n" "___it___ = this;\n" "}\n" "else {\n" "___it___ = null;\n" "}\n" "}\n" "catch ( e ){\n" "print( e );\n" "}\n" "\n" "}\n" "\n" "DBQuery.prototype.toString = function(){\n" "return \"DBQuery: \" + this._ns + \" -> \" + tojson( this.query );\n" "}\n" "\n" "DBQuery.shellBatchSize = 20;\n" ; extern const JSFile query; const JSFile query = { "shell/query.js" , _jscode_raw_query }; const StringData _jscode_raw_collection = "// @file collection.js - DBCollection support in the mongo shell\n" "// db.colName is a DBCollection object\n" "// or db[\"colName\"]\n" "\n" "if ( ( typeof DBCollection ) == \"undefined\" ){\n" "DBCollection = function( mongo , db , shortName , fullName ){\n" "this._mongo = mongo;\n" "this._db = db;\n" "this._shortName = shortName;\n" "this._fullName = fullName;\n" "\n" "this.verify();\n" "}\n" "}\n" "\n" "DBCollection.prototype.verify = function(){\n" "assert( this._fullName , \"no fullName\" );\n" "assert( this._shortName , \"no shortName\" );\n" "assert( this._db , \"no db\" );\n" "\n" "assert.eq( this._fullName , this._db._name + \".\" + this._shortName , \"name mismatch\" );\n" "\n" "assert( this._mongo , \"no mongo in DBCollection\" );\n" "}\n" "\n" "DBCollection.prototype.getName = function(){\n" "return this._shortName;\n" "}\n" "\n" "DBCollection.prototype.help = function () {\n" "var shortName = this.getName();\n" "print(\"DBCollection help\");\n" "print(\"\\tdb.\" + shortName + \".find().help() - show DBCursor help\");\n" "print(\"\\tdb.\" + shortName + \".count()\");\n" "print(\"\\tdb.\" + shortName + \".dataSize()\");\n" "print(\"\\tdb.\" + shortName + \".distinct( key ) - eg. db.\" + shortName + \".distinct( 'x' )\");\n" "print(\"\\tdb.\" + shortName + \".drop() drop the collection\");\n" "print(\"\\tdb.\" + shortName + \".dropIndex(name)\");\n" "print(\"\\tdb.\" + shortName + \".dropIndexes()\");\n" "print(\"\\tdb.\" + shortName + \".ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups\");\n" "print(\"\\tdb.\" + shortName + \".reIndex()\");\n" "print(\"\\tdb.\" + shortName + \".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.\");\n" "print(\"\\t e.g. db.\" + shortName + \".find( {x:77} , {name:1, x:1} )\");\n" "print(\"\\tdb.\" + shortName + \".find(...).count()\");\n" "print(\"\\tdb.\" + shortName + \".find(...).limit(n)\");\n" "print(\"\\tdb.\" + shortName + \".find(...).skip(n)\");\n" "print(\"\\tdb.\" + shortName + \".find(...).sort(...)\");\n" "print(\"\\tdb.\" + shortName + \".findOne([query])\");\n" "print(\"\\tdb.\" + shortName + \".findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )\");\n" "print(\"\\tdb.\" + shortName + \".getDB() get DB object associated with collection\");\n" "print(\"\\tdb.\" + shortName + \".getIndexes()\");\n" "print(\"\\tdb.\" + shortName + \".group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )\");\n" "print(\"\\tdb.\" + shortName + \".mapReduce( mapFunction , reduceFunction , )\");\n" "print(\"\\tdb.\" + shortName + \".remove(query)\");\n" "print(\"\\tdb.\" + shortName + \".renameCollection( newName , ) renames the collection.\");\n" "print(\"\\tdb.\" + shortName + \".runCommand( name , ) runs a db command with the given name where the first param is the collection name\");\n" "print(\"\\tdb.\" + shortName + \".save(obj)\");\n" "print(\"\\tdb.\" + shortName + \".stats()\");\n" "print(\"\\tdb.\" + shortName + \".storageSize() - includes free space allocated to this collection\");\n" "print(\"\\tdb.\" + shortName + \".totalIndexSize() - size in bytes of all the indexes\");\n" "print(\"\\tdb.\" + shortName + \".totalSize() - storage allocated for all data and indexes\");\n" "print(\"\\tdb.\" + shortName + \".update(query, object[, upsert_bool, multi_bool])\");\n" "print(\"\\tdb.\" + shortName + \".validate() - SLOW\");\n" "print(\"\\tdb.\" + shortName + \".getShardVersion() - only for use with sharding\");\n" "return __magicNoPrint;\n" "}\n" "\n" "DBCollection.prototype.getFullName = function(){\n" "return this._fullName;\n" "}\n" "DBCollection.prototype.getMongo = function(){\n" "return this._db.getMongo();\n" "}\n" "DBCollection.prototype.getDB = function(){\n" "return this._db;\n" "}\n" "\n" "DBCollection.prototype._dbCommand = function( cmd , params ){\n" "if ( typeof( cmd ) == \"object\" )\n" "return this._db._dbCommand( cmd );\n" "\n" "var c = {};\n" "c[cmd] = this.getName();\n" "if ( params )\n" "Object.extend( c , params );\n" "return this._db._dbCommand( c );\n" "}\n" "\n" "DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand;\n" "\n" "DBCollection.prototype._massageObject = function( q ){\n" "if ( ! q )\n" "return {};\n" "\n" "var type = typeof q;\n" "\n" "if ( type == \"function\" )\n" "return { $where : q };\n" "\n" "if ( q.isObjectId )\n" "return { _id : q };\n" "\n" "if ( type == \"object\" )\n" "return q;\n" "\n" "if ( type == \"string\" ){\n" "if ( q.length == 24 )\n" "return { _id : q };\n" "\n" "return { $where : q };\n" "}\n" "\n" "throw \"don't know how to massage : \" + type;\n" "\n" "}\n" "\n" "\n" "DBCollection.prototype._validateObject = function( o ){\n" "if ( o._ensureSpecial && o._checkModify )\n" "throw \"can't save a DBQuery object\";\n" "}\n" "\n" "DBCollection._allowedFields = { $id : 1 , $ref : 1 };\n" "\n" "DBCollection.prototype._validateForStorage = function( o ){\n" "this._validateObject( o );\n" "for ( var k in o ){\n" "if ( k.indexOf( \".\" ) >= 0 ) {\n" "throw \"can't have . in field names [\" + k + \"]\" ;\n" "}\n" "\n" "if ( k.indexOf( \"$\" ) == 0 && ! DBCollection._allowedFields[k] ) {\n" "throw \"field names cannot start with $ [\" + k + \"]\";\n" "}\n" "\n" "if ( o[k] !== null && typeof( o[k] ) === \"object\" ) {\n" "this._validateForStorage( o[k] );\n" "}\n" "}\n" "};\n" "\n" "\n" "DBCollection.prototype.find = function( query , fields , limit , skip ){\n" "return new DBQuery( this._mongo , this._db , this ,\n" "this._fullName , this._massageObject( query ) , fields , limit , skip );\n" "}\n" "\n" "DBCollection.prototype.findOne = function( query , fields ){\n" "var cursor = this._mongo.find( this._fullName , this._massageObject( query ) || {} , fields , -1 , 0 , 0 );\n" "if ( ! cursor.hasNext() )\n" "return null;\n" "var ret = cursor.next();\n" "if ( cursor.hasNext() ) throw \"findOne has more than 1 result!\";\n" "if ( ret.$err )\n" "throw \"error \" + tojson( ret );\n" "return ret;\n" "}\n" "\n" "DBCollection.prototype.insert = function( obj , _allow_dot ){\n" "if ( ! obj )\n" "throw \"no object passed to insert!\";\n" "if ( ! _allow_dot ) {\n" "this._validateForStorage( obj );\n" "}\n" "if ( typeof( obj._id ) == \"undefined\" ){\n" "var tmp = obj; // don't want to modify input\n" "obj = {_id: new ObjectId()};\n" "for (var key in tmp){\n" "obj[key] = tmp[key];\n" "}\n" "}\n" "this._mongo.insert( this._fullName , obj );\n" "this._lastID = obj._id;\n" "}\n" "\n" "DBCollection.prototype.remove = function( t , justOne ){\n" "for ( var k in t ){\n" "if ( k == \"_id\" && typeof( t[k] ) == \"undefined\" ){\n" "throw \"can't have _id set to undefined in a remove expression\"\n" "}\n" "}\n" "this._mongo.remove( this._fullName , this._massageObject( t ) , justOne ? true : false );\n" "}\n" "\n" "DBCollection.prototype.update = function( query , obj , upsert , multi ){\n" "assert( query , \"need a query\" );\n" "assert( obj , \"need an object\" );\n" "\n" "var firstKey = null;\n" "for (var k in obj) { firstKey = k; break; }\n" "\n" "if (firstKey != null && firstKey[0] == '$') {\n" "// for mods we only validate partially, for example keys may have dots\n" "this._validateObject( obj );\n" "} else {\n" "// we're basically inserting a brand new object, do full validation\n" "this._validateForStorage( obj );\n" "}\n" "this._mongo.update( this._fullName , query , obj , upsert ? true : false , multi ? true : false );\n" "}\n" "\n" "DBCollection.prototype.save = function( obj ){\n" "if ( obj == null || typeof( obj ) == \"undefined\" )\n" "throw \"can't save a null\";\n" "\n" "if ( typeof( obj ) == \"number\" || typeof( obj) == \"string\" )\n" "throw \"can't save a number or string\"\n" "\n" "if ( typeof( obj._id ) == \"undefined\" ){\n" "obj._id = new ObjectId();\n" "return this.insert( obj );\n" "}\n" "else {\n" "return this.update( { _id : obj._id } , obj , true );\n" "}\n" "}\n" "\n" "DBCollection.prototype._genIndexName = function( keys ){\n" "var name = \"\";\n" "for ( var k in keys ){\n" "var v = keys[k];\n" "if ( typeof v == \"function\" )\n" "continue;\n" "\n" "if ( name.length > 0 )\n" "name += \"_\";\n" "name += k + \"_\";\n" "\n" "if ( typeof v == \"number\" )\n" "name += v;\n" "}\n" "return name;\n" "}\n" "\n" "DBCollection.prototype._indexSpec = function( keys, options ) {\n" "var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) };\n" "\n" "if ( ! options ){\n" "}\n" "else if ( typeof ( options ) == \"string\" )\n" "ret.name = options;\n" "else if ( typeof ( options ) == \"boolean\" )\n" "ret.unique = true;\n" "else if ( typeof ( options ) == \"object\" ){\n" "if ( options.length ){\n" "var nb = 0;\n" "for ( var i=0; i 0 ) {\n" "ret.unique = true;\n" "}\n" "if ( nTrue > 1 ) {\n" "ret.dropDups = true;\n" "}\n" "}\n" "*/\n" "return ret;\n" "}\n" "\n" "DBCollection.prototype.createIndex = function( keys , options ){\n" "var o = this._indexSpec( keys, options );\n" "this._db.getCollection( \"system.indexes\" ).insert( o , true );\n" "}\n" "\n" "DBCollection.prototype.ensureIndex = function( keys , options ){\n" "var name = this._indexSpec( keys, options ).name;\n" "this._indexCache = this._indexCache || {};\n" "if ( this._indexCache[ name ] ){\n" "return;\n" "}\n" "\n" "this.createIndex( keys , options );\n" "if ( this.getDB().getLastError() == \"\" ) {\n" "this._indexCache[name] = true;\n" "}\n" "}\n" "\n" "DBCollection.prototype.resetIndexCache = function(){\n" "this._indexCache = {};\n" "}\n" "\n" "DBCollection.prototype.reIndex = function() {\n" "return this._db.runCommand({ reIndex: this.getName() });\n" "}\n" "\n" "DBCollection.prototype.dropIndexes = function(){\n" "this.resetIndexCache();\n" "\n" "var res = this._db.runCommand( { deleteIndexes: this.getName(), index: \"*\" } );\n" "assert( res , \"no result from dropIndex result\" );\n" "if ( res.ok )\n" "return res;\n" "\n" "if ( res.errmsg.match( /not found/ ) )\n" "return res;\n" "\n" "throw \"error dropping indexes : \" + tojson( res );\n" "}\n" "\n" "\n" "DBCollection.prototype.drop = function(){\n" "if ( arguments.length > 0 )\n" "throw \"drop takes no argument\";\n" "this.resetIndexCache();\n" "var ret = this._db.runCommand( { drop: this.getName() } );\n" "if ( ! ret.ok ){\n" "if ( ret.errmsg == \"ns not found\" )\n" "return false;\n" "throw \"drop failed: \" + tojson( ret );\n" "}\n" "return true;\n" "}\n" "\n" "DBCollection.prototype.findAndModify = function(args){\n" "var cmd = { findandmodify: this.getName() };\n" "for (var key in args){\n" "cmd[key] = args[key];\n" "}\n" "\n" "var ret = this._db.runCommand( cmd );\n" "if ( ! ret.ok ){\n" "if (ret.errmsg == \"No matching object found\"){\n" "return null;\n" "}\n" "throw \"findAndModifyFailed failed: \" + tojson( ret.errmsg );\n" "}\n" "return ret.value;\n" "}\n" "\n" "DBCollection.prototype.renameCollection = function( newName , dropTarget ){\n" "return this._db._adminCommand( { renameCollection : this._fullName ,\n" "to : this._db._name + \".\" + newName ,\n" "dropTarget : dropTarget } )\n" "}\n" "\n" "DBCollection.prototype.validate = function() {\n" "var res = this._db.runCommand( { validate: this.getName() } );\n" "\n" "res.valid = false;\n" "\n" "var raw = res.result || res.raw;\n" "\n" "if ( raw ){\n" "var str = \"-\" + tojson( raw );\n" "res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );\n" "\n" "var p = /lastExtentSize:(\\d+)/;\n" "var r = p.exec( str );\n" "if ( r ){\n" "res.lastExtentSize = Number( r[1] );\n" "}\n" "}\n" "\n" "return res;\n" "}\n" "\n" "DBCollection.prototype.getShardVersion = function(){\n" "return this._db._adminCommand( { getShardVersion : this._fullName } );\n" "}\n" "\n" "DBCollection.prototype.getIndexes = function(){\n" "return this.getDB().getCollection( \"system.indexes\" ).find( { ns : this.getFullName() } ).toArray();\n" "}\n" "\n" "DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes;\n" "DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes;\n" "\n" "DBCollection.prototype.getIndexKeys = function(){\n" "return this.getIndexes().map(\n" "function(i){\n" "return i.key;\n" "}\n" ");\n" "}\n" "\n" "\n" "DBCollection.prototype.count = function( x ){\n" "return this.find( x ).count();\n" "}\n" "\n" "/**\n" "* Drop free lists. Normally not used.\n" "* Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).\n" "*/\n" "DBCollection.prototype.clean = function() {\n" "return this._dbCommand( { clean: this.getName() } );\n" "}\n" "\n" "\n" "\n" "/**\n" "*

    Drop a specified index.

    \n" "*\n" "*

    \n" "* Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to\n" "* see example data.)\n" "*

    \n" "*\n" "*

    Note : alpha: space is not reclaimed

    \n" "* @param {String} name of index to delete.\n" "* @return A result object. result.ok will be true if successful.\n" "*/\n" "DBCollection.prototype.dropIndex = function(index) {\n" "assert(index , \"need to specify index to dropIndex\" );\n" "\n" "if ( ! isString( index ) && isObject( index ) )\n" "index = this._genIndexName( index );\n" "\n" "var res = this._dbCommand( \"deleteIndexes\" ,{ index: index } );\n" "this.resetIndexCache();\n" "return res;\n" "}\n" "\n" "DBCollection.prototype.copyTo = function( newName ){\n" "return this.getDB().eval(\n" "function( collName , newName ){\n" "var from = db[collName];\n" "var to = db[newName];\n" "to.ensureIndex( { _id : 1 } );\n" "var count = 0;\n" "\n" "var cursor = from.find();\n" "while ( cursor.hasNext() ){\n" "var o = cursor.next();\n" "count++;\n" "to.save( o );\n" "}\n" "\n" "return count;\n" "} , this.getName() , newName\n" ");\n" "}\n" "\n" "DBCollection.prototype.getCollection = function( subName ){\n" "return this._db.getCollection( this._shortName + \".\" + subName );\n" "}\n" "\n" "DBCollection.prototype.stats = function( scale ){\n" "return this._db.runCommand( { collstats : this._shortName , scale : scale } );\n" "}\n" "\n" "DBCollection.prototype.dataSize = function(){\n" "return this.stats().size;\n" "}\n" "\n" "DBCollection.prototype.storageSize = function(){\n" "return this.stats().storageSize;\n" "}\n" "\n" "DBCollection.prototype.totalIndexSize = function( verbose ){\n" "var stats = this.stats();\n" "if (verbose){\n" "for (var ns in stats.indexSizes){\n" "print( ns + \"\\t\" + stats.indexSizes[ns] );\n" "}\n" "}\n" "return stats.totalIndexSize;\n" "}\n" "\n" "\n" "DBCollection.prototype.totalSize = function(){\n" "var total = this.storageSize();\n" "var mydb = this._db;\n" "var shortName = this._shortName;\n" "this.getIndexes().forEach(\n" "function( spec ){\n" "var coll = mydb.getCollection( shortName + \".$\" + spec.name );\n" "var mysize = coll.storageSize();\n" "//print( coll + \"\\t\" + mysize + \"\\t\" + tojson( coll.validate() ) );\n" "total += coll.dataSize();\n" "}\n" ");\n" "return total;\n" "}\n" "\n" "\n" "DBCollection.prototype.convertToCapped = function( bytes ){\n" "if ( ! bytes )\n" "throw \"have to specify # of bytes\";\n" "return this._dbCommand( { convertToCapped : this._shortName , size : bytes } )\n" "}\n" "\n" "DBCollection.prototype.exists = function(){\n" "return this._db.system.namespaces.findOne( { name : this._fullName } );\n" "}\n" "\n" "DBCollection.prototype.isCapped = function(){\n" "var e = this.exists();\n" "return ( e && e.options && e.options.capped ) ? true : false;\n" "}\n" "\n" "DBCollection.prototype.distinct = function( keyString , query ){\n" "var res = this._dbCommand( { distinct : this._shortName , key : keyString , query : query || {} } );\n" "if ( ! res.ok )\n" "throw \"distinct failed: \" + tojson( res );\n" "return res.values;\n" "}\n" "\n" "DBCollection.prototype.group = function( params ){\n" "params.ns = this._shortName;\n" "return this._db.group( params );\n" "}\n" "\n" "DBCollection.prototype.groupcmd = function( params ){\n" "params.ns = this._shortName;\n" "return this._db.groupcmd( params );\n" "}\n" "\n" "MapReduceResult = function( db , o ){\n" "Object.extend( this , o );\n" "this._o = o;\n" "this._keys = Object.keySet( o );\n" "this._db = db;\n" "if ( this.result != null ) {\n" "this._coll = this._db.getCollection( this.result );\n" "}\n" "}\n" "\n" "MapReduceResult.prototype._simpleKeys = function(){\n" "return this._o;\n" "}\n" "\n" "MapReduceResult.prototype.find = function(){\n" "if ( this.results )\n" "return this.results;\n" "return DBCollection.prototype.find.apply( this._coll , arguments );\n" "}\n" "\n" "MapReduceResult.prototype.drop = function(){\n" "if ( this._coll ) {\n" "return this._coll.drop();\n" "}\n" "}\n" "\n" "/**\n" "* just for debugging really\n" "*/\n" "MapReduceResult.prototype.convertToSingleObject = function(){\n" "var z = {};\n" "this._coll.find().forEach( function(a){ z[a._id] = a.value; } );\n" "return z;\n" "}\n" "\n" "DBCollection.prototype.convertToSingleObject = function(valueField){\n" "var z = {};\n" "this.find().forEach( function(a){ z[a._id] = a[valueField]; } );\n" "return z;\n" "}\n" "\n" "/**\n" "* @param optional object of optional fields;\n" "*/\n" "DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ){\n" "var c = { mapreduce : this._shortName , map : map , reduce : reduce };\n" "assert( optionsOrOutString , \"need to an optionsOrOutString\" )\n" "\n" "if ( typeof( optionsOrOutString ) == \"string\" )\n" "c[\"out\"] = optionsOrOutString;\n" "else\n" "Object.extend( c , optionsOrOutString );\n" "\n" "var raw = this._db.runCommand( c );\n" "if ( ! raw.ok )\n" "throw \"map reduce failed: \" + tojson( raw );\n" "return new MapReduceResult( this._db , raw );\n" "\n" "}\n" "\n" "DBCollection.prototype.toString = function(){\n" "return this.getFullName();\n" "}\n" "\n" "DBCollection.prototype.toString = function(){\n" "return this.getFullName();\n" "}\n" "\n" "\n" "DBCollection.prototype.tojson = DBCollection.prototype.toString;\n" "\n" "DBCollection.prototype.shellPrint = DBCollection.prototype.toString;\n" "\n" "DBCollection.autocomplete = function(obj){\n" "var colls = DB.autocomplete(obj.getDB());\n" "var ret = [];\n" "for (var i=0; i