// db.js var DB; (function() { if (DB === undefined) { DB = function( mongo , name ){ this._mongo = mongo; this._name = name; } } DB.prototype.getMongo = function(){ assert( this._mongo , "why no mongo!" ); return this._mongo; } DB.prototype.getSiblingDB = function( name ){ return this.getMongo().getDB( name ); } DB.prototype.getSisterDB = DB.prototype.getSiblingDB; DB.prototype.getName = function(){ return this._name; } DB.prototype.stats = function(scale){ return this.runCommand( { dbstats : 1 , scale : scale } ); } DB.prototype.getCollection = function( name ){ return new DBCollection( this._mongo , this , name , this._name + "." + name ); } DB.prototype.commandHelp = function( name ){ var c = {}; c[name] = 1; c.help = true; var res = this.runCommand( c ); if ( ! res.ok ) throw Error(res.errmsg); return res.help; } DB.prototype.runCommand = function( obj, extra ){ if ( typeof( obj ) == "string" ){ var n = {}; n[obj] = 1; obj = n; if ( extra && typeof( extra ) == "object" ) { for ( var x in extra ) { n[x] = extra[x]; } } } return this.getCollection( "$cmd" ).findOne( obj ); } DB.prototype._dbCommand = DB.prototype.runCommand; DB.prototype.adminCommand = function( obj ){ if ( this._name == "admin" ) return this.runCommand( obj ); return this.getSiblingDB( "admin" ).runCommand( obj ); } DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name /** Create a new collection in the database. Normally, collection creation is automatic. You would use this function if you wish to specify special options on creation. If the collection already exists, no action occurs.

Options:

Example:

db.createCollection("movies", { size: 10 * 1024 * 1024, capped:true } ); * @param {String} name Name of new collection to create * @param {Object} options Object with options for call. Options are listed above. * @return SOMETHING_FIXME */ DB.prototype.createCollection = function(name, opt) { var options = opt || {}; var cmd = { create: name }; if (options.max != undefined) cmd.max = options.max; if (options.autoIndexId != undefined) cmd.autoIndexId = options.autoIndexId; if (options.capped != undefined) cmd.capped = options.capped; if (options.size != undefined) cmd.size = options.size; if (options.usePowerOf2Sizes != undefined) cmd.flags = options.usePowerOf2Sizes ? 1 : 0; var res = this._dbCommand(cmd); return res; } /** * @deprecated use getProfilingStatus * Returns the current profiling level of this database * @return SOMETHING_FIXME or null on error */ DB.prototype.getProfilingLevel = function() { var res = this._dbCommand( { profile: -1 } ); return res ? res.was : null; } /** * @return the current profiling status * example { was : 0, slowms : 100 } * @return SOMETHING_FIXME or null on error */ DB.prototype.getProfilingStatus = function() { var res = this._dbCommand( { profile: -1 } ); if ( ! res.ok ) throw Error( "profile command failed: " + tojson( res ) ); delete res.ok return res; } /** Erase the entire database. (!) * @return Object returned has member ok set to true if operation succeeds, false otherwise. */ DB.prototype.dropDatabase = function() { if ( arguments.length ) throw Error("dropDatabase doesn't take arguments"); return this._dbCommand( { dropDatabase: 1 } ); } /** * Shuts down the database. Must be run while using the admin database. * @param opts Options for shutdown. Possible options are: * - force: (boolean) if the server should shut down, even if there is no * up-to-date slave * - timeoutSecs: (number) the server will continue checking over timeoutSecs * if any other servers have caught up enough for it to shut down. */ DB.prototype.shutdownServer = function(opts) { if( "admin" != this._name ){ return "shutdown command only works with the admin database; try 'use admin'"; } cmd = {"shutdown" : 1}; opts = opts || {}; for (var o in opts) { cmd[o] = opts[o]; } try { var res = this.runCommand(cmd); if( res ) throw Error( "shutdownServer failed: " + res.errmsg ); throw Error( "shutdownServer failed" ); } catch ( e ){ assert( tojson( e ).indexOf( "error doing query: failed" ) >= 0 , "unexpected error: " + tojson( e ) ); print( "server should be down..." ); } } /** Clone database on another server to here.

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

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

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

This is a low level administrative function is not typically used. * @param {String} from mongod instance from which to clnoe (dbhostname:port). May not be this mongod instance, as clone from self is not allowed. * @param {String} collection name of collection to clone. * @param {Object} query query specifying which elements of collection are to be cloned. * @return Object returned has member ok set to true if operation succeeds, false otherwise. * See also: db.cloneDatabase() */ DB.prototype.cloneCollection = function(from, collection, query) { assert( isString(from) && from.length ); assert( isString(collection) && collection.length ); collection = this._name + "." + collection; query = query || {}; return this._dbCommand( { cloneCollection:collection, from:from, query:query } ); } /** Copy database from one server or name to another server or name. Generally, you should dropDatabase() first as otherwise the copied information will MERGE into whatever data is already present in this database (and you will get duplicate objects in collections potentially.) For security reasons this function only works when executed on the "admin" db. However, if you have access to said db, you can copy any database from one place to another. This method provides a way to "rename" a database by copying it to a new db name and location. Additionally, it effectively provides a repair facility. * @param {String} fromdb database name from which to copy. * @param {String} todb database name to copy to. * @param {String} fromhost hostname of the database (and optionally, ":port") from which to copy the data. default if unspecified is to copy from self. * @return Object returned has member ok set to true if operation succeeds, false otherwise. * See also: db.clone() */ DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password) { assert( isString(fromdb) && fromdb.length ); assert( isString(todb) && todb.length ); fromhost = fromhost || ""; if ( username && password ) { var n = this._adminCommand( { copydbgetnonce : 1, fromhost:fromhost } ); return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb, username:username, nonce:n.nonce, key:this.__pwHash( n.nonce, username, password ) } ); } else { return this._adminCommand( { copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb } ); } } /** Repair database. * @return Object returned has member ok set to true if operation succeeds, false otherwise. */ DB.prototype.repairDatabase = function() { return this._dbCommand( { repairDatabase: 1 } ); } DB.prototype.help = function() { print("DB methods:"); print("\tdb.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]"); print("\tdb.auth(username, password)"); print("\tdb.cloneDatabase(fromhost)"); print("\tdb.commandHelp(name) returns the help for the command"); print("\tdb.copyDatabase(fromdb, todb, fromhost)"); print("\tdb.createCollection(name, { size : ..., capped : ..., max : ... } )"); print("\tdb.createUser(userDocument)"); print("\tdb.currentOp() displays currently executing operations in the db"); print("\tdb.dropDatabase()"); print("\tdb.eval(func, args) run code server-side"); print("\tdb.fsyncLock() flush data to disk and lock server for backups"); print("\tdb.fsyncUnlock() unlocks server following a db.fsyncLock()"); print("\tdb.getCollection(cname) same as db['cname'] or db.cname"); print("\tdb.getCollectionNames()"); print("\tdb.getLastError() - just returns the err msg string"); print("\tdb.getLastErrorObj() - return full status object"); print("\tdb.getLogComponents()"); print("\tdb.getMongo() get the server connection object"); print("\tdb.getMongo().setSlaveOk() allow queries on a replication slave server"); print("\tdb.getName()"); print("\tdb.getPrevError()"); print("\tdb.getProfilingLevel() - deprecated"); print("\tdb.getProfilingStatus() - returns if profiling is on and slow threshold"); print("\tdb.getReplicationInfo()"); print("\tdb.getSiblingDB(name) get the db at the same server as this one"); print("\tdb.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set"); print("\tdb.hostInfo() get details about the server's host"); print("\tdb.isMaster() check replica primary status"); print("\tdb.killOp(opid) kills the current operation in the db"); print("\tdb.listCommands() lists all the db commands"); print("\tdb.loadServerScripts() loads all the scripts in db.system.js"); print("\tdb.logout()"); print("\tdb.printCollectionStats()"); print("\tdb.printReplicationInfo()"); print("\tdb.printShardingStatus()"); print("\tdb.printSlaveReplicationInfo()"); print("\tdb.dropUser(username)"); print("\tdb.repairDatabase()"); print("\tdb.resetError()"); print("\tdb.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }"); print("\tdb.serverStatus()"); print("\tdb.setLogLevel(level,)"); print("\tdb.setProfilingLevel(level,) 0=off 1=slow 2=all"); print("\tdb.setWriteConcern( ) - sets the write concern for writes to the db"); print("\tdb.unsetWriteConcern( ) - unsets the write concern for writes to the db"); print("\tdb.setVerboseShell(flag) display extra information in shell output"); print("\tdb.shutdownServer()"); print("\tdb.stats()"); print("\tdb.version() current version of the server"); return __magicNoPrint; } DB.prototype.printCollectionStats = function(scale) { if (arguments.length > 1) { print("printCollectionStats() has a single optional argument (scale)"); return; } if (typeof scale != 'undefined') { if(typeof scale != 'number') { print("scale has to be a number >= 1"); return; } if (scale < 1) { print("scale has to be >= 1"); return; } } var mydb = this; this.getCollectionNames().forEach( function(z) { print( z ); printjson( mydb.getCollection(z).stats(scale) ); print( "---" ); } ); } /** *

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

* *

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

* *

Levels :

*