diff options
author | Jonathan Abrahams <jonathan@mongodb.com> | 2016-03-09 11:51:31 -0500 |
---|---|---|
committer | Jonathan Abrahams <jonathan@mongodb.com> | 2016-03-09 11:51:31 -0500 |
commit | a025d43f3ce2efc1fb1282a718f5d286fa0a4dc1 (patch) | |
tree | a71ec459d031c8b76ebe1efc20a1150339161949 /src/mongo/shell/collection.js | |
parent | 4019e38d105597df8320e4958cc2be784157378d (diff) | |
download | mongo-a025d43f3ce2efc1fb1282a718f5d286fa0a4dc1.tar.gz |
SERVER-22469 Format JS code with approved style in src/mongo/shell & src/mongo/scripting
Diffstat (limited to 'src/mongo/shell/collection.js')
-rw-r--r-- | src/mongo/shell/collection.js | 1205 |
1 files changed, 656 insertions, 549 deletions
diff --git a/src/mongo/shell/collection.js b/src/mongo/shell/collection.js index 7acb73bf71c..566913867d3 100644 --- a/src/mongo/shell/collection.js +++ b/src/mongo/shell/collection.js @@ -2,8 +2,8 @@ // db.colName is a DBCollection object // or db["colName"] -if ( ( typeof DBCollection ) == "undefined" ){ - DBCollection = function( mongo , db , shortName , fullName ){ +if ((typeof DBCollection) == "undefined") { + DBCollection = function(mongo, db, shortName, fullName) { this._mongo = mongo; this._db = db; this._shortName = shortName; @@ -13,116 +13,170 @@ if ( ( typeof DBCollection ) == "undefined" ){ }; } -DBCollection.prototype.verify = function(){ - assert( this._fullName , "no fullName" ); - assert( this._shortName , "no shortName" ); - assert( this._db , "no db" ); +DBCollection.prototype.verify = function() { + assert(this._fullName, "no fullName"); + assert(this._shortName, "no shortName"); + assert(this._db, "no db"); - assert.eq( this._fullName , this._db._name + "." + this._shortName , "name mismatch" ); + assert.eq(this._fullName, this._db._name + "." + this._shortName, "name mismatch"); - assert( this._mongo , "no mongo in DBCollection" ); - assert( this.getMongo() , "no mongo from getMongo()" ); + assert(this._mongo, "no mongo in DBCollection"); + assert(this.getMongo(), "no mongo from getMongo()"); }; -DBCollection.prototype.getName = function(){ +DBCollection.prototype.getName = function() { return this._shortName; }; -DBCollection.prototype.help = function () { +DBCollection.prototype.help = function() { var shortName = this.getName(); print("DBCollection help"); print("\tdb." + shortName + ".find().help() - show DBCursor help"); - print("\tdb." + shortName + ".bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j"); - print("\tdb." + shortName + ".count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS"); - print("\tdb." + shortName + ".copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied."); - print("\tdb." + shortName + ".convertToCapped(maxBytes) - calls {convertToCapped:'" + shortName + "', size:maxBytes}} command"); + print( + "\tdb." + shortName + + ".bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j"); + print( + "\tdb." + shortName + + ".count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS"); + print( + "\tdb." + shortName + + ".copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied."); + print("\tdb." + shortName + ".convertToCapped(maxBytes) - calls {convertToCapped:'" + + shortName + "', size:maxBytes}} command"); print("\tdb." + shortName + ".createIndex(keypattern[,options])"); print("\tdb." + shortName + ".createIndexes([keypatterns], <options>)"); print("\tdb." + shortName + ".dataSize()"); - print("\tdb." + shortName + ".deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j"); - print("\tdb." + shortName + ".deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j"); - print("\tdb." + shortName + ".distinct( key, query, <optional params> ) - e.g. db." + shortName + ".distinct( 'x' ), optional parameters are: maxTimeMS"); + print( + "\tdb." + shortName + + ".deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j"); + print( + "\tdb." + shortName + + ".deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j"); + print("\tdb." + shortName + ".distinct( key, query, <optional params> ) - e.g. db." + + shortName + ".distinct( 'x' ), optional parameters are: maxTimeMS"); print("\tdb." + shortName + ".drop() drop the collection"); - print("\tdb." + shortName + ".dropIndex(index) - e.g. db." + shortName + ".dropIndex( \"indexName\" ) or db." + shortName + ".dropIndex( { \"indexKey\" : 1 } )"); + print("\tdb." + shortName + ".dropIndex(index) - e.g. db." + shortName + + ".dropIndex( \"indexName\" ) or db." + shortName + ".dropIndex( { \"indexKey\" : 1 } )"); print("\tdb." + shortName + ".dropIndexes()"); - print("\tdb." + shortName + ".ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead"); + print("\tdb." + shortName + + ".ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead"); print("\tdb." + shortName + ".explain().help() - show explain help"); print("\tdb." + shortName + ".reIndex()"); - print("\tdb." + shortName + ".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return."); - print("\t e.g. db." + shortName + ".find( {x:77} , {name:1, x:1} )"); + print( + "\tdb." + shortName + + ".find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return."); + print("\t e.g. db." + shortName + + ".find( {x:77} , {name:1, x:1} )"); print("\tdb." + shortName + ".find(...).count()"); print("\tdb." + shortName + ".find(...).limit(n)"); print("\tdb." + shortName + ".find(...).skip(n)"); print("\tdb." + shortName + ".find(...).sort(...)"); print("\tdb." + shortName + ".findOne([query], [fields], [options], [readConcern])"); - print("\tdb." + shortName + ".findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS"); - print("\tdb." + shortName + ".findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument"); - print("\tdb." + shortName + ".findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument"); + print( + "\tdb." + shortName + + ".findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS"); + print( + "\tdb." + shortName + + ".findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument"); + print( + "\tdb." + shortName + + ".findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument"); print("\tdb." + shortName + ".getDB() get DB object associated with collection"); print("\tdb." + shortName + ".getPlanCache() get query plan cache associated with collection"); print("\tdb." + shortName + ".getIndexes()"); print("\tdb." + shortName + ".group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )"); print("\tdb." + shortName + ".insert(obj)"); - print("\tdb." + shortName + ".insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j"); - print("\tdb." + shortName + ".insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j"); + print( + "\tdb." + shortName + + ".insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j"); + print( + "\tdb." + shortName + + ".insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j"); print("\tdb." + shortName + ".mapReduce( mapFunction , reduceFunction , <optional params> )"); - print("\tdb." + shortName + ".aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor"); + print( + "\tdb." + shortName + + ".aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor"); print("\tdb." + shortName + ".remove(query)"); - print("\tdb." + shortName + ".replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j"); - print("\tdb." + shortName + ".renameCollection( newName , <dropTarget> ) renames the collection."); - print("\tdb." + shortName + ".runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name"); + print( + "\tdb." + shortName + + ".replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j"); + print("\tdb." + shortName + + ".renameCollection( newName , <dropTarget> ) renames the collection."); + print( + "\tdb." + shortName + + ".runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name"); print("\tdb." + shortName + ".save(obj)"); print("\tdb." + shortName + ".stats({scale: N, indexDetails: true/false, " + "indexDetailsKey: <index key>, indexDetailsName: <index name>})"); - // print("\tdb." + shortName + ".diskStorageStats({[extent: <num>,] [granularity: <bytes>,] ...}) - analyze record layout on disk"); - // print("\tdb." + shortName + ".pagesInRAM({[extent: <num>,] [granularity: <bytes>,] ...}) - analyze resident memory pages"); - print("\tdb." + shortName + ".storageSize() - includes free space allocated to this collection"); + // print("\tdb." + shortName + ".diskStorageStats({[extent: <num>,] [granularity: <bytes>,] + // ...}) - analyze record layout on disk"); + // print("\tdb." + shortName + ".pagesInRAM({[extent: <num>,] [granularity: <bytes>,] ...}) - + // analyze resident memory pages"); + print("\tdb." + shortName + + ".storageSize() - includes free space allocated to this collection"); print("\tdb." + shortName + ".totalIndexSize() - size in bytes of all the indexes"); print("\tdb." + shortName + ".totalSize() - storage allocated for all data and indexes"); - print("\tdb." + shortName + ".update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi"); - print("\tdb." + shortName + ".updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j"); - print("\tdb." + shortName + ".updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j"); + print( + "\tdb." + shortName + + ".update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi"); + print( + "\tdb." + shortName + + ".updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j"); + print( + "\tdb." + shortName + + ".updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j"); print("\tdb." + shortName + ".validate( <full> ) - SLOW"); print("\tdb." + shortName + ".getShardVersion() - only for use with sharding"); - print("\tdb." + shortName + ".getShardDistribution() - prints statistics about data distribution in the cluster"); - print("\tdb." + shortName + ".getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function"); - print("\tdb." + shortName + ".getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set"); - print("\tdb." + shortName + ".setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection"); - print("\tdb." + shortName + ".unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection"); - // print("\tdb." + shortName + ".getDiskStorageStats({...}) - prints a summary of disk usage statistics"); - // print("\tdb." + shortName + ".getPagesInRAM({...}) - prints a summary of storage pages currently in physical memory"); + print("\tdb." + shortName + + ".getShardDistribution() - prints statistics about data distribution in the cluster"); + print( + "\tdb." + shortName + + ".getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function"); + print( + "\tdb." + shortName + + ".getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set"); + print( + "\tdb." + shortName + + ".setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection"); + print( + "\tdb." + shortName + + ".unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection"); + // print("\tdb." + shortName + ".getDiskStorageStats({...}) - prints a summary of disk usage + // statistics"); + // print("\tdb." + shortName + ".getPagesInRAM({...}) - prints a summary of storage pages + // currently in physical memory"); return __magicNoPrint; }; -DBCollection.prototype.getFullName = function(){ +DBCollection.prototype.getFullName = function() { return this._fullName; }; -DBCollection.prototype.getMongo = function(){ +DBCollection.prototype.getMongo = function() { return this._db.getMongo(); }; -DBCollection.prototype.getDB = function(){ +DBCollection.prototype.getDB = function() { return this._db; }; -DBCollection.prototype._makeCommand = function (cmd, params) { +DBCollection.prototype._makeCommand = function(cmd, params) { var c = {}; c[cmd] = this.getName(); - if ( params ) + if (params) Object.extend(c, params); return c; }; -DBCollection.prototype._dbCommand = function( cmd , params ){ - if (typeof( cmd ) === "object") +DBCollection.prototype._dbCommand = function(cmd, params) { + if (typeof(cmd) === "object") return this._db._dbCommand(cmd, {}, this.getQueryOptions()); return this._db._dbCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions()); }; // Like _dbCommand, but applies $readPreference -DBCollection.prototype._dbReadCommand = function( cmd , params ){ - if (typeof( cmd ) === "object") - return this._db._dbReadCommand( cmd , {}, this.getQueryOptions()); +DBCollection.prototype._dbReadCommand = function(cmd, params) { + if (typeof(cmd) === "object") + return this._db._dbReadCommand(cmd, {}, this.getQueryOptions()); return this._db._dbReadCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions()); }; @@ -131,69 +185,90 @@ DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand; DBCollection.prototype.runReadCommand = DBCollection.prototype._dbReadCommand; -DBCollection.prototype._massageObject = function( q ){ - if ( ! q ) +DBCollection.prototype._massageObject = function(q) { + if (!q) return {}; var type = typeof q; - if ( type == "function" ) - return { $where : q }; + if (type == "function") + return { + $where: q + }; - if ( q.isObjectId ) - return { _id : q }; + if (q.isObjectId) + return { + _id: q + }; - if ( type == "object" ) + if (type == "object") return q; - if ( type == "string" ){ - if ( q.length == 24 ) - return { _id : q }; + if (type == "string") { + if (q.length == 24) + return { + _id: q + }; - return { $where : q }; + return { + $where: q + }; } - throw Error( "don't know how to massage : " + type ); + throw Error("don't know how to massage : " + type); }; - -DBCollection.prototype._validateObject = function( o ){ +DBCollection.prototype._validateObject = function(o) { // Hidden property for testing purposes. - if (this.getMongo()._skipValidation) return; + if (this.getMongo()._skipValidation) + return; if (typeof(o) != "object") - throw Error( "attempted to save a " + typeof(o) + " value. document expected." ); + throw Error("attempted to save a " + typeof(o) + " value. document expected."); - if ( o._ensureSpecial && o._checkModify ) - throw Error( "can't save a DBQuery object" ); + if (o._ensureSpecial && o._checkModify) + throw Error("can't save a DBQuery object"); }; -DBCollection._allowedFields = { $id : 1 , $ref : 1 , $db : 1 }; +DBCollection._allowedFields = { + $id: 1, + $ref: 1, + $db: 1 +}; -DBCollection.prototype._validateForStorage = function( o ){ +DBCollection.prototype._validateForStorage = function(o) { // Hidden property for testing purposes. - if (this.getMongo()._skipValidation) return; + if (this.getMongo()._skipValidation) + return; - this._validateObject( o ); - for ( var k in o ){ - if ( k.indexOf( "." ) >= 0 ) { - throw Error( "can't have . in field names [" + k + "]" ); + this._validateObject(o); + for (var k in o) { + if (k.indexOf(".") >= 0) { + throw Error("can't have . in field names [" + k + "]"); } - if ( k.indexOf( "$" ) == 0 && ! DBCollection._allowedFields[k] ) { - throw Error( "field names cannot start with $ [" + k + "]" ); + if (k.indexOf("$") == 0 && !DBCollection._allowedFields[k]) { + throw Error("field names cannot start with $ [" + k + "]"); } - if ( o[k] !== null && typeof( o[k] ) === "object" ) { - this._validateForStorage( o[k] ); + if (o[k] !== null && typeof(o[k]) === "object") { + this._validateForStorage(o[k]); } } }; -DBCollection.prototype.find = function( query , fields , limit , skip, batchSize, options ){ - var cursor = new DBQuery( this._mongo , this._db , this , - this._fullName , this._massageObject( query ) , fields , limit , skip , batchSize , options || this.getQueryOptions() ); +DBCollection.prototype.find = function(query, fields, limit, skip, batchSize, options) { + var cursor = new DBQuery(this._mongo, + this._db, + this, + this._fullName, + this._massageObject(query), + fields, + limit, + skip, + batchSize, + options || this.getQueryOptions()); var connObj = this.getMongo(); var readPrefMode = connObj.getReadPrefMode(); @@ -204,37 +279,36 @@ DBCollection.prototype.find = function( query , fields , limit , skip, batchSize return cursor; }; -DBCollection.prototype.findOne = function( query , fields, options, readConcern ){ - var cursor = this.find(query, fields, -1 /* limit */, 0 /* skip*/, - 0 /* batchSize */, options); +DBCollection.prototype.findOne = function(query, fields, options, readConcern) { + var cursor = this.find(query, fields, -1 /* limit */, 0 /* skip*/, 0 /* batchSize */, options); - if ( readConcern ) { + if (readConcern) { cursor = cursor.readConcern(readConcern); } - if ( ! cursor.hasNext() ) + if (!cursor.hasNext()) return null; var ret = cursor.next(); - if ( cursor.hasNext() ) throw Error( "findOne has more than 1 result!" ); - if ( ret.$err ) + if (cursor.hasNext()) + throw Error("findOne has more than 1 result!"); + if (ret.$err) throw _getErrorWithCode(ret, "error " + tojson(ret)); return ret; }; -DBCollection.prototype.insert = function( obj , options, _allow_dot ){ - if ( ! obj ) - throw Error( "no object passed to insert!" ); +DBCollection.prototype.insert = function(obj, options, _allow_dot) { + if (!obj) + throw Error("no object passed to insert!"); var flags = 0; var wc = undefined; var allowDottedFields = false; - if ( options === undefined ) { + if (options === undefined) { // do nothing - } - else if ( typeof(options) == 'object' ) { + } else if (typeof(options) == 'object') { if (options.ordered === undefined) { - //do nothing, like above + // do nothing, like above } else { flags = options.ordered ? 0 : 1; } @@ -254,10 +328,10 @@ DBCollection.prototype.insert = function( obj , options, _allow_dot ){ wc = this.getWriteConcern(); var result = undefined; - var startTime = (typeof(_verboseShell) === 'undefined' || - !_verboseShell) ? 0 : new Date().getTime(); + var startTime = + (typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime(); - if ( this.getMongo().writeMode() != "legacy" ) { + if (this.getMongo().writeMode() != "legacy") { // Bit 1 of option flag is continueOnError. Bit 0 (stop on error) is the default. var bulk = ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp(); var isMultiInsert = Array.isArray(obj); @@ -266,8 +340,7 @@ DBCollection.prototype.insert = function( obj , options, _allow_dot ){ obj.forEach(function(doc) { bulk.insert(doc); }); - } - else { + } else { bulk.insert(obj); } @@ -275,34 +348,32 @@ DBCollection.prototype.insert = function( obj , options, _allow_dot ){ result = bulk.execute(wc); if (!isMultiInsert) result = result.toSingleResult(); - } - catch( ex ) { - if ( ex instanceof BulkWriteError ) { + } catch (ex) { + if (ex instanceof BulkWriteError) { result = isMultiInsert ? ex.toResult() : ex.toSingleResult(); - } - else if ( ex instanceof WriteCommandError ) { + } else if (ex instanceof WriteCommandError) { result = isMultiInsert ? ex : ex.toSingleResult(); - } - else { + } else { // Other exceptions thrown throw Error(ex); } } - } - else { - if ( ! _allow_dot ) { - this._validateForStorage( obj ); + } else { + if (!_allow_dot) { + this._validateForStorage(obj); } - if ( typeof( obj._id ) == "undefined" && ! Array.isArray( obj ) ){ - var tmp = obj; // don't want to modify input - obj = {_id: new ObjectId()}; - for (var key in tmp){ + if (typeof(obj._id) == "undefined" && !Array.isArray(obj)) { + var tmp = obj; // don't want to modify input + obj = { + _id: new ObjectId() + }; + for (var key in tmp) { obj[key] = tmp[key]; } } - this.getMongo().insert( this._fullName , obj, flags ); + this.getMongo().insert(this._fullName, obj, flags); // enforce write concern, if required if (wc) @@ -316,11 +387,12 @@ DBCollection.prototype.insert = function( obj , options, _allow_dot ){ DBCollection.prototype._validateRemoveDoc = function(doc) { // Hidden property for testing purposes. - if (this.getMongo()._skipValidation) return; + if (this.getMongo()._skipValidation) + return; for (var k in doc) { - if (k == "_id" && typeof( doc[k] ) == "undefined") { - throw new Error("can't have _id set to undefined in a remove expression"); + if (k == "_id" && typeof(doc[k]) == "undefined") { + throw new Error("can't have _id set to undefined in a remove expression"); } } }; @@ -329,8 +401,9 @@ DBCollection.prototype._validateRemoveDoc = function(doc) { * Does validation of the remove args. Throws if the parse is not successful, otherwise * returns a document {query: <query>, justOne: <limit>, wc: <writeConcern>}. */ -DBCollection.prototype._parseRemove = function( t , justOne ) { - if (undefined === t) throw Error("remove needs a query"); +DBCollection.prototype._parseRemove = function(t, justOne) { + if (undefined === t) + throw Error("remove needs a query"); var query = this._massageObject(t); @@ -349,52 +422,50 @@ DBCollection.prototype._parseRemove = function( t , justOne ) { wc = this.getWriteConcern(); } - return {"query": query, "justOne": justOne, "wc": wc}; + return { + "query": query, + "justOne": justOne, + "wc": wc + }; }; -DBCollection.prototype.remove = function( t , justOne ){ +DBCollection.prototype.remove = function(t, justOne) { var parsed = this._parseRemove(t, justOne); var query = parsed.query; var justOne = parsed.justOne; var wc = parsed.wc; var result = undefined; - var startTime = (typeof(_verboseShell) === 'undefined' || - !_verboseShell) ? 0 : new Date().getTime(); + var startTime = + (typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime(); - - if ( this.getMongo().writeMode() != "legacy" ) { + if (this.getMongo().writeMode() != "legacy") { var bulk = this.initializeOrderedBulkOp(); var removeOp = bulk.find(query); if (justOne) { removeOp.removeOne(); - } - else { + } else { removeOp.remove(); } try { result = bulk.execute(wc).toSingleResult(); - } - catch( ex ) { - if ( ex instanceof BulkWriteError || ex instanceof WriteCommandError ) { + } catch (ex) { + if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) { result = ex.toSingleResult(); - } - else { + } else { // Other exceptions thrown throw Error(ex); } } - } - else { + } else { this._validateRemoveDoc(t); - this.getMongo().remove(this._fullName, query, justOne ); + this.getMongo().remove(this._fullName, query, justOne); // enforce write concern, if required if (wc) result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc); - } this._printExtraInfo("Removed", startTime); @@ -403,17 +474,21 @@ DBCollection.prototype.remove = function( t , justOne ){ DBCollection.prototype._validateUpdateDoc = function(doc) { // Hidden property for testing purposes. - if (this.getMongo()._skipValidation) return; + if (this.getMongo()._skipValidation) + return; var firstKey = null; - for (var key in doc) { firstKey = key; break; } + for (var key in doc) { + firstKey = key; + break; + } if (firstKey != null && firstKey[0] == '$') { // for mods we only validate partially, for example keys may have dots - this._validateObject( doc ); + this._validateObject(doc); } else { // we're basically inserting a brand new object, do full validation - this._validateForStorage( doc ); + this._validateForStorage(doc); } }; @@ -423,13 +498,15 @@ DBCollection.prototype._validateUpdateDoc = function(doc) { * * Throws if the arguments are invalid. */ -DBCollection.prototype._parseUpdate = function( query , obj , upsert , multi ){ - if (!query) throw Error("need a query"); - if (!obj) throw Error("need an object"); +DBCollection.prototype._parseUpdate = function(query, obj, upsert, multi) { + if (!query) + throw Error("need a query"); + if (!obj) + throw Error("need an object"); var wc = undefined; // can pass options via object for improved readability - if ( typeof(upsert) === "object" ) { + if (typeof(upsert) === "object") { if (multi) { throw Error("Fourth argument must be empty when specifying " + "upsert and multi with an object."); @@ -449,14 +526,16 @@ DBCollection.prototype._parseUpdate = function( query , obj , upsert , multi ){ wc = this.getWriteConcern(); } - return {"query": query, - "obj": obj, - "upsert": upsert, - "multi": multi, - "wc": wc}; + return { + "query": query, + "obj": obj, + "upsert": upsert, + "multi": multi, + "wc": wc + }; }; -DBCollection.prototype.update = function( query , obj , upsert , multi ){ +DBCollection.prototype.update = function(query, obj, upsert, multi) { var parsed = this._parseUpdate(query, obj, upsert, multi); var query = parsed.query; var obj = parsed.obj; @@ -465,10 +544,10 @@ DBCollection.prototype.update = function( query , obj , upsert , multi ){ var wc = parsed.wc; var result = undefined; - var startTime = (typeof(_verboseShell) === 'undefined' || - !_verboseShell) ? 0 : new Date().getTime(); + var startTime = + (typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime(); - if ( this.getMongo().writeMode() != "legacy" ) { + if (this.getMongo().writeMode() != "legacy") { var bulk = this.initializeOrderedBulkOp(); var updateOp = bulk.find(query); @@ -478,25 +557,21 @@ DBCollection.prototype.update = function( query , obj , upsert , multi ){ if (multi) { updateOp.update(obj); - } - else { + } else { updateOp.updateOne(obj); } try { result = bulk.execute(wc).toSingleResult(); - } - catch( ex ) { - if ( ex instanceof BulkWriteError || ex instanceof WriteCommandError ) { + } catch (ex) { + if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) { result = ex.toSingleResult(); - } - else { + } else { // Other exceptions thrown throw Error(ex); } } - } - else { + } else { this._validateUpdateDoc(obj); this.getMongo().update(this._fullName, query, obj, upsert, multi); @@ -510,30 +585,29 @@ DBCollection.prototype.update = function( query , obj , upsert , multi ){ return result; }; -DBCollection.prototype.save = function( obj , opts ){ - if ( obj == null ) +DBCollection.prototype.save = function(obj, opts) { + if (obj == null) throw Error("can't save a null"); - if ( typeof( obj ) == "number" || typeof( obj) == "string" ) + if (typeof(obj) == "number" || typeof(obj) == "string") throw Error("can't save a number or string"); - if ( typeof( obj._id ) == "undefined" ){ + if (typeof(obj._id) == "undefined") { obj._id = new ObjectId(); - return this.insert( obj , opts ); - } - else { - return this.update( { _id : obj._id } , obj , Object.merge({ upsert:true }, opts)); + return this.insert(obj, opts); + } else { + return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts)); } }; -DBCollection.prototype._genIndexName = function( keys ){ +DBCollection.prototype._genIndexName = function(keys) { var name = ""; - for ( var k in keys ){ + for (var k in keys) { var v = keys[k]; - if ( typeof v == "function" ) + if (typeof v == "function") continue; - if ( name.length > 0 ) + if (name.length > 0) name += "_"; name += k + "_"; @@ -542,48 +616,49 @@ DBCollection.prototype._genIndexName = function( keys ){ return name; }; -DBCollection.prototype._indexSpec = function( keys, options ) { - var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) }; +DBCollection.prototype._indexSpec = function(keys, options) { + var ret = { + ns: this._fullName, + key: keys, + name: this._genIndexName(keys) + }; - if ( ! options ){ - } - else if ( typeof ( options ) == "string" ) + if (!options) { + } else if (typeof(options) == "string") ret.name = options; - else if ( typeof ( options ) == "boolean" ) + else if (typeof(options) == "boolean") ret.unique = true; - else if ( typeof ( options ) == "object" ){ - if ( Array.isArray(options) ){ + else if (typeof(options) == "object") { + if (Array.isArray(options)) { if (options.length > 3) { throw new Error("Index options that are supplied in array form may only specify" + " three values: name, unique, dropDups"); } var nb = 0; - for ( var i=0; i<options.length; i++ ){ - if ( typeof ( options[i] ) == "string" ) + for (var i = 0; i < options.length; i++) { + if (typeof(options[i]) == "string") ret.name = options[i]; - else if ( typeof( options[i] ) == "boolean" ){ - if ( options[i] ){ - if ( nb == 0 ) + else if (typeof(options[i]) == "boolean") { + if (options[i]) { + if (nb == 0) ret.unique = true; - if ( nb == 1 ) + if (nb == 1) ret.dropDups = true; } nb++; } } + } else { + Object.extend(ret, options); } - else { - Object.extend( ret , options ); - } - } - else { - throw Error( "can't handle: " + typeof( options ) ); + } else { + throw Error("can't handle: " + typeof(options)); } return ret; }; -DBCollection.prototype.createIndex = function(keys , options) { +DBCollection.prototype.createIndex = function(keys, options) { return this.createIndexes([keys], options); }; @@ -595,34 +670,37 @@ DBCollection.prototype.createIndexes = function(keys, options) { if (this.getMongo().writeMode() == "commands") { for (i = 0; i++; i < indexSpecs.length) { - delete (indexSpecs[i].ns); // ns is passed to the first element in the command. + delete (indexSpecs[i].ns); // ns is passed to the first element in the command. } - return this._db.runCommand({createIndexes: this.getName(), indexes: indexSpecs}); - } - else if(this.getMongo().writeMode() == "compatibility") { + return this._db.runCommand({createIndexes: this.getName(), indexes: indexSpecs}); + } else if (this.getMongo().writeMode() == "compatibility") { // Use the downconversion machinery of the bulk api to do a safe write, report response as a // command response - var result = this._db.getCollection("system.indexes").insert(indexSpecs , 0, true); + var result = this._db.getCollection("system.indexes").insert(indexSpecs, 0, true); if (result.hasWriteErrors() || result.hasWriteConcernError()) { // Return the first error - var error = result.hasWriteErrors() ? result.getWriteErrors()[0] : - result.getWriteConcernError(); - return {ok : 0.0, code : error.code, errmsg : error.errmsg}; - } - else { - return {ok : 1.0}; + var error = result.hasWriteErrors() ? result.getWriteErrors()[0] + : result.getWriteConcernError(); + return { + ok: 0.0, + code: error.code, + errmsg: error.errmsg + }; + } else { + return { + ok: 1.0 + }; } - } - else { + } else { this._db.getCollection("system.indexes").insert(indexSpecs, 0, true); } }; -DBCollection.prototype.ensureIndex = function( keys , options ){ +DBCollection.prototype.ensureIndex = function(keys, options) { var result = this.createIndex(keys, options); - if ( this.getMongo().writeMode() != "legacy" ) { + if (this.getMongo().writeMode() != "legacy") { return result; } @@ -634,46 +712,47 @@ DBCollection.prototype.ensureIndex = function( keys , options ){ }; DBCollection.prototype.reIndex = function() { - return this._db.runCommand({ reIndex: this.getName() }); + return this._db.runCommand({reIndex: this.getName()}); }; -DBCollection.prototype.dropIndexes = function(){ - if ( arguments.length ) +DBCollection.prototype.dropIndexes = function() { + if (arguments.length) throw Error("dropIndexes doesn't take arguments"); - var res = this._db.runCommand( { deleteIndexes: this.getName(), index: "*" } ); - assert( res , "no result from dropIndex result" ); - if ( res.ok ) + var res = this._db.runCommand({deleteIndexes: this.getName(), index: "*"}); + assert(res, "no result from dropIndex result"); + if (res.ok) return res; - if ( res.errmsg.match( /not found/ ) ) + if (res.errmsg.match(/not found/)) return res; throw _getErrorWithCode(res, "error dropping indexes : " + tojson(res)); }; - -DBCollection.prototype.drop = function(){ - if ( arguments.length > 0 ) +DBCollection.prototype.drop = function() { + if (arguments.length > 0) throw Error("drop takes no argument"); - var ret = this._db.runCommand( { drop: this.getName() } ); - if ( ! ret.ok ){ - if ( ret.errmsg == "ns not found" ) + var ret = this._db.runCommand({drop: this.getName()}); + if (!ret.ok) { + if (ret.errmsg == "ns not found") return false; throw _getErrorWithCode(ret, "drop failed: " + tojson(ret)); } return true; }; -DBCollection.prototype.findAndModify = function(args){ - var cmd = { findandmodify: this.getName() }; - for (var key in args){ +DBCollection.prototype.findAndModify = function(args) { + var cmd = { + findandmodify: this.getName() + }; + for (var key in args) { cmd[key] = args[key]; } - var ret = this._db.runCommand( cmd ); - if ( ! ret.ok ){ - if (ret.errmsg == "No matching object found"){ + var ret = this._db.runCommand(cmd); + if (!ret.ok) { + if (ret.errmsg == "No matching object found") { return null; } throw _getErrorWithCode(ret, "findAndModifyFailed failed: " + tojson(ret)); @@ -681,15 +760,17 @@ DBCollection.prototype.findAndModify = function(args){ return ret.value; }; -DBCollection.prototype.renameCollection = function( newName , dropTarget ){ - return this._db._adminCommand( { renameCollection : this._fullName , - to : this._db._name + "." + newName , - dropTarget : dropTarget } ); +DBCollection.prototype.renameCollection = function(newName, dropTarget) { + return this._db._adminCommand({ + renameCollection: this._fullName, + to: this._db._name + "." + newName, + dropTarget: dropTarget + }); }; // Display verbose information about the operation DBCollection.prototype._printExtraInfo = function(action, startTime) { - if ( typeof _verboseShell === 'undefined' || !_verboseShell ) { + if (typeof _verboseShell === 'undefined' || !_verboseShell) { __callLastError = true; return; } @@ -716,14 +797,16 @@ DBCollection.prototype._printExtraInfo = function(action, startTime) { }; DBCollection.prototype.validate = function(full) { - var cmd = { validate: this.getName() }; + var cmd = { + validate: this.getName() + }; - if (typeof(full) == 'object') // support arbitrary options here + if (typeof(full) == 'object') // support arbitrary options here Object.extend(cmd, full); else cmd.full = full; - var res = this._db.runCommand( cmd ); + var res = this._db.runCommand(cmd); if (typeof(res.valid) == 'undefined') { // old-style format just put everything in a string. Now using proper fields @@ -732,14 +815,14 @@ DBCollection.prototype.validate = function(full) { var raw = res.result || res.raw; - if ( raw ){ - var str = "-" + tojson( raw ); - res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) ); + if (raw) { + var str = "-" + tojson(raw); + res.valid = !(str.match(/exception/) || str.match(/corrupt/)); var p = /lastExtentSize:(\d+)/; - var r = p.exec( str ); - if ( r ){ - res.lastExtentSize = Number( r[1] ); + var r = p.exec(str); + if (r) { + res.lastExtentSize = Number(r[1]); } } } @@ -753,8 +836,12 @@ DBCollection.prototype.validate = function(full) { * getDiskStorageStats provides a human-readable summary of the command output */ DBCollection.prototype.diskStorageStats = function(opt) { - var cmd = { storageDetails: this.getName(), analyze: 'diskStorage' }; - if (typeof(opt) == 'object') Object.extend(cmd, opt); + var cmd = { + storageDetails: this.getName(), + analyze: 'diskStorage' + }; + if (typeof(opt) == 'object') + Object.extend(cmd, opt); var res = this._db.runCommand(cmd); if (!res.ok && res.errmsg.match(/no such cmd/)) { @@ -782,14 +869,13 @@ DBCollection.prototype.getDiskStorageStats = function(params) { var bar = _barFormat([ [data.bsonBytes / data.onDiskBytes, "="], [(data.recBytes - data.bsonBytes) / data.onDiskBytes, "-"] - ], BAR_WIDTH); - - return sh._dataFormat(data.onDiskBytes).pad(9) + " " + - data.numEntries.toFixed(0).pad(10) + " " + - bar + " " + - (data.bsonBytes / data.onDiskBytes).toPercentStr().pad(8) + " " + - (data.recBytes / data.onDiskBytes).toPercentStr().pad(8) + " " + - (data.recBytes / data.bsonBytes).toFixed(4).pad(8); + ], + BAR_WIDTH); + + return sh._dataFormat(data.onDiskBytes).pad(9) + " " + data.numEntries.toFixed(0).pad(10) + + " " + bar + " " + (data.bsonBytes / data.onDiskBytes).toPercentStr().pad(8) + " " + + (data.recBytes / data.onDiskBytes).toPercentStr().pad(8) + " " + + (data.recBytes / data.bsonBytes).toFixed(4).pad(8); }; var printExtent = function(ex, rng) { @@ -829,8 +915,12 @@ DBCollection.prototype.getDiskStorageStats = function(params) { * getPagesInRAM provides a human-readable summary of the command output */ DBCollection.prototype.pagesInRAM = function(opt) { - var cmd = { storageDetails: this.getName(), analyze: 'pagesInRAM' }; - if (typeof(opt) == 'object') Object.extend(cmd, opt); + var cmd = { + storageDetails: this.getName(), + analyze: 'pagesInRAM' + }; + if (typeof(opt) == 'object') + Object.extend(cmd, opt); var res = this._db.runCommand(cmd); if (!res.ok && res.errmsg.match(/no such cmd/)) { @@ -849,9 +939,8 @@ DBCollection.prototype.getPagesInRAM = function(params) { var BAR_WIDTH = 70; var formatExtentData = function(data) { - return "size".pad(8) + " " + - _barFormat([ [data.inMem, '='] ], BAR_WIDTH) + " " + - data.inMem.toPercentStr().pad(7); + return "size".pad(8) + " " + _barFormat([[data.inMem, '=']], BAR_WIDTH) + " " + + data.inMem.toPercentStr().pad(7); }; var printExtent = function(ex, rng) { @@ -871,11 +960,16 @@ DBCollection.prototype.getPagesInRAM = function(params) { line = "\t" + sh._dataFormat(ex.sliceBytes * c).pad(8) + " ["; } var inMem = ex.slices[c]; - if (inMem <= .001) line += " "; - else if (inMem <= .25) line += "."; - else if (inMem <= .5) line += "_"; - else if (inMem <= .75) line += "="; - else line += "#"; + if (inMem <= .001) + line += " "; + else if (inMem <= .25) + line += "."; + else if (inMem <= .5) + line += "_"; + else if (inMem <= .75) + line += "="; + else + line += "#"; } print(line + "]"); print(); @@ -903,34 +997,35 @@ DBCollection.prototype.getPagesInRAM = function(params) { } }; -DBCollection.prototype.getShardVersion = function(){ - return this._db._adminCommand( { getShardVersion : this._fullName } ); +DBCollection.prototype.getShardVersion = function() { + return this._db._adminCommand({getShardVersion: this._fullName}); }; -DBCollection.prototype._getIndexesSystemIndexes = function(filter){ - var si = this.getDB().getCollection( "system.indexes" ); - var query = { ns : this.getFullName() }; +DBCollection.prototype._getIndexesSystemIndexes = function(filter) { + var si = this.getDB().getCollection("system.indexes"); + var query = { + ns: this.getFullName() + }; if (filter) query = Object.extend(query, filter); - return si.find( query ).toArray(); + return si.find(query).toArray(); }; -DBCollection.prototype._getIndexesCommand = function(filter){ - var res = this.runCommand( "listIndexes", filter ); - - if ( !res.ok ) { +DBCollection.prototype._getIndexesCommand = function(filter) { + var res = this.runCommand("listIndexes", filter); - if ( res.code == 59 ) { + if (!res.ok) { + if (res.code == 59) { // command doesn't exist, old mongod return null; } - if ( res.code == 26 ) { + if (res.code == 26) { // NamespaceNotFound, for compatability, return [] return []; } - if ( res.errmsg && res.errmsg.startsWith( "no such cmd" ) ) { + if (res.errmsg && res.errmsg.startsWith("no such cmd")) { return null; } @@ -940,9 +1035,9 @@ DBCollection.prototype._getIndexesCommand = function(filter){ return new DBCommandCursor(this._mongo, res).toArray(); }; -DBCollection.prototype.getIndexes = function(filter){ +DBCollection.prototype.getIndexes = function(filter) { var res = this._getIndexesCommand(filter); - if ( res ) { + if (res) { return res; } return this._getIndexesSystemIndexes(filter); @@ -951,22 +1046,21 @@ DBCollection.prototype.getIndexes = function(filter){ DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes; DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes; -DBCollection.prototype.getIndexKeys = function(){ - return this.getIndexes().map( - function(i){ - return i.key; - } - ); +DBCollection.prototype.getIndexKeys = function() { + return this.getIndexes().map(function(i) { + return i.key; + }); }; - DBCollection.prototype.hashAllDocs = function() { - var cmd = { dbhash : 1, - collections : [ this._shortName ] }; - var res = this._dbCommand( cmd ); + var cmd = { + dbhash: 1, + collections: [this._shortName] + }; + var res = this._dbCommand(cmd); var hash = res.collections[this._shortName]; - assert( hash ); - assert( typeof(hash) == "string" ); + assert(hash); + assert(typeof(hash) == "string"); return hash; }; @@ -974,7 +1068,8 @@ DBCollection.prototype.hashAllDocs = function() { * <p>Drop a specified index.</p> * * <p> - * "index" is the name of the index in the system.indexes name field (run db.system.indexes.find() to + * "index" is the name of the index in the system.indexes name field (run db.system.indexes.find() + *to * see example data), or an object holding the key(s) used to create the index. * For example: * db.collectionName.dropIndex( "myIndexName" ); @@ -984,34 +1079,32 @@ DBCollection.prototype.hashAllDocs = function() { * @param {String} name or key object of index to delete. * @return A result object. result.ok will be true if successful. */ -DBCollection.prototype.dropIndex = function(index) { - assert(index, "need to specify index to dropIndex" ); - var res = this._dbCommand( "deleteIndexes", { index: index } ); +DBCollection.prototype.dropIndex = function(index) { + assert(index, "need to specify index to dropIndex"); + var res = this._dbCommand("deleteIndexes", {index: index}); return res; }; -DBCollection.prototype.copyTo = function( newName ){ - return this.getDB().eval( - function( collName , newName ){ - var from = db[collName]; - var to = db[newName]; - to.ensureIndex( { _id : 1 } ); - var count = 0; +DBCollection.prototype.copyTo = function(newName) { + return this.getDB().eval(function(collName, newName) { + var from = db[collName]; + var to = db[newName]; + to.ensureIndex({_id: 1}); + var count = 0; - var cursor = from.find(); - while ( cursor.hasNext() ){ - var o = cursor.next(); - count++; - to.save( o ); - } + var cursor = from.find(); + while (cursor.hasNext()) { + var o = cursor.next(); + count++; + to.save(o); + } - return count; - } , this.getName() , newName - ); + return count; + }, this.getName(), newName); }; -DBCollection.prototype.getCollection = function( subName ){ - return this._db.getCollection( this._shortName + "." + subName ); +DBCollection.prototype.getCollection = function(subName) { + return this._db.getCollection(this._shortName + "." + subName); }; /** @@ -1041,7 +1134,8 @@ DBCollection.prototype.stats = function(args) { } var getIndexName = function(collection, indexKey) { - if (!isObject(indexKey)) return undefined; + if (!isObject(indexKey)) + return undefined; var indexName; collection.getIndexes().forEach(function(spec) { if (friendlyEqual(spec.key, options.indexDetailsKey)) { @@ -1051,18 +1145,20 @@ DBCollection.prototype.stats = function(args) { return indexName; }; - var filterIndexName = - options.indexDetailsName || getIndexName(this, options.indexDetailsKey); + var filterIndexName = options.indexDetailsName || getIndexName(this, options.indexDetailsKey); var updateStats = function(stats, keepIndexDetails, indexName) { - if (!stats.indexDetails) return; + if (!stats.indexDetails) + return; if (!keepIndexDetails) { delete stats.indexDetails; return; } - if (!indexName) return; + if (!indexName) + return; for (var key in stats.indexDetails) { - if (key == indexName) continue; + if (key == indexName) + continue; delete stats.indexDetails[key]; } }; @@ -1078,26 +1174,25 @@ DBCollection.prototype.stats = function(args) { return res; }; -DBCollection.prototype.dataSize = function(){ +DBCollection.prototype.dataSize = function() { return this.stats().size; }; -DBCollection.prototype.storageSize = function(){ +DBCollection.prototype.storageSize = function() { return this.stats().storageSize; }; -DBCollection.prototype.totalIndexSize = function( verbose ){ +DBCollection.prototype.totalIndexSize = function(verbose) { var stats = this.stats(); - if (verbose){ - for (var ns in stats.indexSizes){ - print( ns + "\t" + stats.indexSizes[ns] ); + if (verbose) { + for (var ns in stats.indexSizes) { + print(ns + "\t" + stats.indexSizes[ns]); } } return stats.totalIndexSize; }; - -DBCollection.prototype.totalSize = function(){ +DBCollection.prototype.totalSize = function() { var total = this.storageSize(); var totalIndexSize = this.totalIndexSize(); if (totalIndexSize) { @@ -1106,33 +1201,31 @@ DBCollection.prototype.totalSize = function(){ return total; }; - -DBCollection.prototype.convertToCapped = function( bytes ){ - if ( ! bytes ) +DBCollection.prototype.convertToCapped = function(bytes) { + if (!bytes) throw Error("have to specify # of bytes"); - return this._dbCommand( { convertToCapped : this._shortName , size : bytes } ); + return this._dbCommand({convertToCapped: this._shortName, size: bytes}); }; -DBCollection.prototype.exists = function(){ - var res = this._db.runCommand( "listCollections", - { filter : { name : this._shortName } } ); - if ( res.ok ) { - var cursor = new DBCommandCursor( this._mongo, res ); - if ( !cursor.hasNext() ) +DBCollection.prototype.exists = function() { + var res = this._db.runCommand("listCollections", {filter: {name: this._shortName}}); + if (res.ok) { + var cursor = new DBCommandCursor(this._mongo, res); + if (!cursor.hasNext()) return null; return cursor.next(); } - if ( res.errmsg && res.errmsg.startsWith( "no such cmd" ) ) { - return this._db.system.namespaces.findOne( { name : this._fullName } ); + if (res.errmsg && res.errmsg.startsWith("no such cmd")) { + return this._db.system.namespaces.findOne({name: this._fullName}); } throw _getErrorWithCode(res, "listCollections failed: " + tojson(res)); }; -DBCollection.prototype.isCapped = function(){ +DBCollection.prototype.isCapped = function() { var e = this.exists(); - return ( e && e.options && e.options.capped ) ? true : false; + return (e && e.options && e.options.capped) ? true : false; }; // @@ -1175,7 +1268,9 @@ DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) { // Assign the cleaned up options aggregateOptions = copy; // Create the initial command document - var cmd = {pipeline: pipeline}; + var cmd = { + pipeline: pipeline + }; Object.extend(cmd, aggregateOptions); if (!('cursor' in cmd)) { @@ -1190,28 +1285,30 @@ DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) { var doAgg = function(cmd) { // if we don't have an out stage, we could run on a secondary // so we need to attach readPreference - return hasOutStage ? - this.runCommand("aggregate", cmd) : this.runReadCommand("aggregate", cmd); + return hasOutStage ? this.runCommand("aggregate", cmd) + : this.runReadCommand("aggregate", cmd); }.bind(this); var res = doAgg(cmd); - if (!res.ok - && (res.code == 17020 || res.errmsg == "unrecognized field \"cursor") - && !("cursor" in aggregateOptions)) { - // If the command failed because cursors aren't supported and the user didn't explicitly - // request a cursor, try again without requesting a cursor. - delete cmd.cursor; - - res = doAgg(cmd); - - if ('result' in res && !("cursor" in res)) { - // convert old-style output to cursor-style output - res.cursor = {ns: '', id: NumberLong(0)}; - res.cursor.firstBatch = res.result; - delete res.result; - } + if (!res.ok && (res.code == 17020 || res.errmsg == "unrecognized field \"cursor") && + !("cursor" in aggregateOptions)) { + // If the command failed because cursors aren't supported and the user didn't explicitly + // request a cursor, try again without requesting a cursor. + delete cmd.cursor; + + res = doAgg(cmd); + + if ('result' in res && !("cursor" in res)) { + // convert old-style output to cursor-style output + res.cursor = { + ns: '', + id: NumberLong(0) + }; + res.cursor.firstBatch = res.result; + delete res.result; } + } assert.commandWorked(res, "aggregate failed"); @@ -1222,38 +1319,38 @@ DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) { return res; }; -DBCollection.prototype.group = function( params ){ +DBCollection.prototype.group = function(params) { params.ns = this._shortName; - return this._db.group( params ); + return this._db.group(params); }; -DBCollection.prototype.groupcmd = function( params ){ +DBCollection.prototype.groupcmd = function(params) { params.ns = this._shortName; - return this._db.groupcmd( params ); + return this._db.groupcmd(params); }; -MapReduceResult = function( db , o ){ - Object.extend( this , o ); +MapReduceResult = function(db, o) { + Object.extend(this, o); this._o = o; - this._keys = Object.keySet( o ); + this._keys = Object.keySet(o); this._db = db; - if ( this.result != null ) { - this._coll = this._db.getCollection( this.result ); + if (this.result != null) { + this._coll = this._db.getCollection(this.result); } }; -MapReduceResult.prototype._simpleKeys = function(){ +MapReduceResult.prototype._simpleKeys = function() { return this._o; }; -MapReduceResult.prototype.find = function(){ - if ( this.results ) +MapReduceResult.prototype.find = function() { + if (this.results) return this.results; - return DBCollection.prototype.find.apply( this._coll , arguments ); + return DBCollection.prototype.find.apply(this._coll, arguments); }; -MapReduceResult.prototype.drop = function(){ - if ( this._coll ) { +MapReduceResult.prototype.drop = function() { + if (this._coll) { return this._coll.drop(); } }; @@ -1261,30 +1358,38 @@ MapReduceResult.prototype.drop = function(){ /** * just for debugging really */ -MapReduceResult.prototype.convertToSingleObject = function(){ +MapReduceResult.prototype.convertToSingleObject = function() { var z = {}; var it = this.results != null ? this.results : this._coll.find(); - it.forEach( function(a){ z[a._id] = a.value; } ); + it.forEach(function(a) { + z[a._id] = a.value; + }); return z; }; -DBCollection.prototype.convertToSingleObject = function(valueField){ +DBCollection.prototype.convertToSingleObject = function(valueField) { var z = {}; - this.find().forEach( function(a){ z[a._id] = a[valueField]; } ); + this.find().forEach(function(a) { + z[a._id] = a[valueField]; + }); return z; }; /** * @param optional object of optional fields; */ -DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ){ - var c = { mapreduce : this._shortName , map : map , reduce : reduce }; - assert( optionsOrOutString , "need to supply an optionsOrOutString" ); +DBCollection.prototype.mapReduce = function(map, reduce, optionsOrOutString) { + var c = { + mapreduce: this._shortName, + map: map, + reduce: reduce + }; + assert(optionsOrOutString, "need to supply an optionsOrOutString"); - if ( typeof( optionsOrOutString ) == "string" ) + if (typeof(optionsOrOutString) == "string") c["out"] = optionsOrOutString; else - Object.extend( c , optionsOrOutString ); + Object.extend(c, optionsOrOutString); var raw; @@ -1296,41 +1401,41 @@ DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ) raw = this._db.runCommand(c); } - if ( ! raw.ok ){ + if (!raw.ok) { __mrerror__ = raw; throw _getErrorWithCode(raw, "map reduce failed:" + tojson(raw)); } - return new MapReduceResult( this._db , raw ); + return new MapReduceResult(this._db, raw); }; -DBCollection.prototype.toString = function(){ +DBCollection.prototype.toString = function() { return this.getFullName(); }; -DBCollection.prototype.toString = function(){ +DBCollection.prototype.toString = function() { return this.getFullName(); }; - DBCollection.prototype.tojson = DBCollection.prototype.toString; DBCollection.prototype.shellPrint = DBCollection.prototype.toString; -DBCollection.autocomplete = function(obj){ +DBCollection.autocomplete = function(obj) { var colls = DB.autocomplete(obj.getDB()); var ret = []; - for (var i=0; i<colls.length; i++){ + for (var i = 0; i < colls.length; i++) { var c = colls[i]; - if (c.length <= obj.getName().length) continue; - if (c.slice(0,obj.getName().length+1) != obj.getName()+'.') continue; + if (c.length <= obj.getName().length) + continue; + if (c.slice(0, obj.getName().length + 1) != obj.getName() + '.') + continue; - ret.push(c.slice(obj.getName().length+1)); + ret.push(c.slice(obj.getName().length + 1)); } return ret; }; - // Sharding additions /* @@ -1342,186 +1447,187 @@ Loading custom sharding extensions... true > var collection = db.getMongo().getCollection("foo.bar") -> collection.getShardDistribution() // prints statistics related to the collection's data distribution +> collection.getShardDistribution() // prints statistics related to the collection's data +distribution -> collection.getSplitKeysForChunks() // generates split points for all chunks in the collection, based on the +> collection.getSplitKeysForChunks() // generates split points for all chunks in the collection, +based on the // default maxChunkSize or alternately a specified chunk size > collection.getSplitKeysForChunks( 10 ) // Mb -> var splitter = collection.getSplitKeysForChunks() // by default, the chunks are not split, the keys are just - // found. A splitter function is returned which will actually +> var splitter = collection.getSplitKeysForChunks() // by default, the chunks are not split, the +keys are just + // found. A splitter function is returned which +will actually // do the splits. > splitter() // ! Actually executes the splits on the cluster ! */ -DBCollection.prototype.getShardDistribution = function(){ - - var stats = this.stats(); - - if( ! stats.sharded ){ - print( "Collection " + this + " is not sharded." ); - return; - } - - var config = this.getMongo().getDB("config"); +DBCollection.prototype.getShardDistribution = function() { - var numChunks = 0; + var stats = this.stats(); - for( var shard in stats.shards ){ + if (!stats.sharded) { + print("Collection " + this + " is not sharded."); + return; + } - var shardDoc = config.shards.findOne({ _id : shard }); + var config = this.getMongo().getDB("config"); - print( "\nShard " + shard + " at " + shardDoc.host ); + var numChunks = 0; - var shardStats = stats.shards[ shard ]; + for (var shard in stats.shards) { + var shardDoc = config.shards.findOne({_id: shard}); - var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray(); + print("\nShard " + shard + " at " + shardDoc.host); - numChunks += chunks.length; + var shardStats = stats.shards[shard]; - var estChunkData = shardStats.size / chunks.length; - var estChunkCount = Math.floor( shardStats.count / chunks.length ); + var chunks = config.chunks.find({_id: sh._collRE(this), shard: shard}).toArray(); - print( " data : " + sh._dataFormat( shardStats.size ) + - " docs : " + shardStats.count + - " chunks : " + chunks.length ); - print( " estimated data per chunk : " + sh._dataFormat( estChunkData ) ); - print( " estimated docs per chunk : " + estChunkCount ); + numChunks += chunks.length; - } + var estChunkData = shardStats.size / chunks.length; + var estChunkCount = Math.floor(shardStats.count / chunks.length); - print( "\nTotals" ); - print( " data : " + sh._dataFormat( stats.size ) + - " docs : " + stats.count + - " chunks : " + numChunks ); - for( var shard in stats.shards ){ + print(" data : " + sh._dataFormat(shardStats.size) + " docs : " + shardStats.count + + " chunks : " + chunks.length); + print(" estimated data per chunk : " + sh._dataFormat(estChunkData)); + print(" estimated docs per chunk : " + estChunkCount); + } - var shardStats = stats.shards[ shard ]; + print("\nTotals"); + print(" data : " + sh._dataFormat(stats.size) + " docs : " + stats.count + " chunks : " + + numChunks); + for (var shard in stats.shards) { + var shardStats = stats.shards[shard]; - var estDataPercent = Math.floor( shardStats.size / stats.size * 10000 ) / 100; - var estDocPercent = Math.floor( shardStats.count / stats.count * 10000 ) / 100; + var estDataPercent = Math.floor(shardStats.size / stats.size * 10000) / 100; + var estDocPercent = Math.floor(shardStats.count / stats.count * 10000) / 100; - print( " Shard " + shard + " contains " + estDataPercent + "% data, " + estDocPercent + "% docs in cluster, " + - "avg obj size on shard : " + sh._dataFormat( stats.shards[ shard ].avgObjSize ) ); - } + print(" Shard " + shard + " contains " + estDataPercent + "% data, " + estDocPercent + + "% docs in cluster, " + "avg obj size on shard : " + + sh._dataFormat(stats.shards[shard].avgObjSize)); + } - print( "\n" ); + print("\n"); }; +DBCollection.prototype.getSplitKeysForChunks = function(chunkSize) { -DBCollection.prototype.getSplitKeysForChunks = function( chunkSize ){ - - var stats = this.stats(); - - if( ! stats.sharded ){ - print( "Collection " + this + " is not sharded." ); - return; - } - - var config = this.getMongo().getDB("config"); - - if( ! chunkSize ){ - chunkSize = config.settings.findOne({ _id : "chunksize" }).value; - print( "Chunk size not set, using default of " + chunkSize + "MB" ); - } - else{ - print( "Using chunk size of " + chunkSize + "MB" ); - } - - var shardDocs = config.shards.find().toArray(); - - var allSplitPoints = {}; - var numSplits = 0; + var stats = this.stats(); - for( var i = 0; i < shardDocs.length; i++ ){ + if (!stats.sharded) { + print("Collection " + this + " is not sharded."); + return; + } - var shardDoc = shardDocs[i]; - var shard = shardDoc._id; - var host = shardDoc.host; - var sconn = new Mongo( host ); + var config = this.getMongo().getDB("config"); - var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray(); + if (!chunkSize) { + chunkSize = config.settings.findOne({_id: "chunksize"}).value; + print("Chunk size not set, using default of " + chunkSize + "MB"); + } else { + print("Using chunk size of " + chunkSize + "MB"); + } - print( "\nGetting split points for chunks on shard " + shard + " at " + host ); + var shardDocs = config.shards.find().toArray(); - var splitPoints = []; + var allSplitPoints = {}; + var numSplits = 0; - for( var j = 0; j < chunks.length; j++ ){ - var chunk = chunks[j]; - var result = sconn.getDB("admin").runCommand({ splitVector : this + "", min : chunk.min, max : chunk.max, maxChunkSize : chunkSize }); - if( ! result.ok ){ - print( " Had trouble getting split keys for chunk " + sh._pchunk( chunk ) + " :\n" ); - printjson( result ); - } - else{ - splitPoints = splitPoints.concat( result.splitKeys ); + for (var i = 0; i < shardDocs.length; i++) { + var shardDoc = shardDocs[i]; + var shard = shardDoc._id; + var host = shardDoc.host; + var sconn = new Mongo(host); - if( result.splitKeys.length > 0 ) - print( " Added " + result.splitKeys.length + " split points for chunk " + sh._pchunk( chunk ) ); - } - } + var chunks = config.chunks.find({_id: sh._collRE(this), shard: shard}).toArray(); - print( "Total splits for shard " + shard + " : " + splitPoints.length ); + print("\nGetting split points for chunks on shard " + shard + " at " + host); - numSplits += splitPoints.length; - allSplitPoints[ shard ] = splitPoints; + var splitPoints = []; - } + for (var j = 0; j < chunks.length; j++) { + var chunk = chunks[j]; + var result = sconn.getDB("admin").runCommand( + {splitVector: this + "", min: chunk.min, max: chunk.max, maxChunkSize: chunkSize}); + if (!result.ok) { + print(" Had trouble getting split keys for chunk " + sh._pchunk(chunk) + " :\n"); + printjson(result); + } else { + splitPoints = splitPoints.concat(result.splitKeys); - // Get most recent migration - var migration = config.changelog.find({ what : /^move.*/ }).sort({ time : -1 }).limit( 1 ).toArray(); - if( migration.length == 0 ) - print( "\nNo migrations found in changelog." ); - else { - migration = migration[0]; - print( "\nMost recent migration activity was on " + migration.ns + " at " + migration.time ); - } + if (result.splitKeys.length > 0) + print(" Added " + result.splitKeys.length + " split points for chunk " + + sh._pchunk(chunk)); + } + } - var admin = this.getMongo().getDB("admin"); - var coll = this; - var splitFunction = function(){ + print("Total splits for shard " + shard + " : " + splitPoints.length); - // Turn off the balancer, just to be safe - print( "Turning off balancer..." ); - config.settings.update({ _id : "balancer" }, { $set : { stopped : true } }, true ); - print( "Sleeping for 30s to allow balancers to detect change. To be extra safe, check config.changelog" + - " for recent migrations." ); - sleep( 30000 ); + numSplits += splitPoints.length; + allSplitPoints[shard] = splitPoints; + } - for( var shard in allSplitPoints ){ - for( var i = 0; i < allSplitPoints[ shard ].length; i++ ){ - var splitKey = allSplitPoints[ shard ][i]; - print( "Splitting at " + tojson( splitKey ) ); - printjson( admin.runCommand({ split : coll + "", middle : splitKey }) ); - } - } + // Get most recent migration + var migration = config.changelog.find({what: /^move.*/}).sort({time: -1}).limit(1).toArray(); + if (migration.length == 0) + print("\nNo migrations found in changelog."); + else { + migration = migration[0]; + print("\nMost recent migration activity was on " + migration.ns + " at " + migration.time); + } + + var admin = this.getMongo().getDB("admin"); + var coll = this; + var splitFunction = function() { + + // Turn off the balancer, just to be safe + print("Turning off balancer..."); + config.settings.update({_id: "balancer"}, {$set: {stopped: true}}, true); + print( + "Sleeping for 30s to allow balancers to detect change. To be extra safe, check config.changelog" + + " for recent migrations."); + sleep(30000); + + for (var shard in allSplitPoints) { + for (var i = 0; i < allSplitPoints[shard].length; i++) { + var splitKey = allSplitPoints[shard][i]; + print("Splitting at " + tojson(splitKey)); + printjson(admin.runCommand({split: coll + "", middle: splitKey})); + } + } - print( "Turning the balancer back on." ); - config.settings.update({ _id : "balancer" }, { $set : { stopped : false } } ); - sleep( 1 ); - }; + print("Turning the balancer back on."); + config.settings.update({_id: "balancer"}, {$set: {stopped: false}}); + sleep(1); + }; - splitFunction.getSplitPoints = function(){ return allSplitPoints; }; + splitFunction.getSplitPoints = function() { + return allSplitPoints; + }; - print( "\nGenerated " + numSplits + " split keys, run output function to perform splits.\n" + - " ex : \n" + - " > var splitter = <collection>.getSplitKeysForChunks()\n" + - " > splitter() // Execute splits on cluster !\n" ); + print("\nGenerated " + numSplits + " split keys, run output function to perform splits.\n" + + " ex : \n" + " > var splitter = <collection>.getSplitKeysForChunks()\n" + + " > splitter() // Execute splits on cluster !\n"); - return splitFunction; + return splitFunction; }; -DBCollection.prototype.setSlaveOk = function( value ) { - if( value == undefined ) value = true; +DBCollection.prototype.setSlaveOk = function(value) { + if (value == undefined) + value = true; this._slaveOk = value; }; DBCollection.prototype.getSlaveOk = function() { - if (this._slaveOk != undefined) return this._slaveOk; + if (this._slaveOk != undefined) + return this._slaveOk; return this._db.getSlaveOk(); }; @@ -1535,18 +1641,17 @@ DBCollection.prototype.getQueryOptions = function() { * Returns a PlanCache for the collection. */ DBCollection.prototype.getPlanCache = function() { - return new PlanCache( this ); + return new PlanCache(this); }; // Overrides connection-level settings. // -DBCollection.prototype.setWriteConcern = function( wc ) { - if ( wc instanceof WriteConcern ) { +DBCollection.prototype.setWriteConcern = function(wc) { + if (wc instanceof WriteConcern) { this._writeConcern = wc; - } - else { - this._writeConcern = new WriteConcern( wc ); + } else { + this._writeConcern = new WriteConcern(wc); } }; @@ -1554,7 +1659,6 @@ DBCollection.prototype.getWriteConcern = function() { if (this._writeConcern) return this._writeConcern; - if (this._db.getWriteConcern()) return this._db.getWriteConcern(); @@ -1611,33 +1715,37 @@ DBCollection.prototype.count = function(query, options) { }; /** -* The distinct command returns returns a list of distinct values for the given key across a collection. +* The distinct command returns returns a list of distinct values for the given key across a +*collection. * * @method * @param {string} key Field of the document to find distinct values for. -* @param {object} query The query for filtering the set of documents to which we apply the distinct filter. +* @param {object} query The query for filtering the set of documents to which we apply the distinct +*filter. * @param {object} [options=null] Optional settings. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. * @return {object} */ -DBCollection.prototype.distinct = function(keyString, query, options){ +DBCollection.prototype.distinct = function(keyString, query, options) { var opts = Object.extend({}, options || {}); var keyStringType = typeof keyString; var queryType = typeof query; if (keyStringType != "string") { - throw new Error("The first argument to the distinct command must be a string but was a " + keyStringType); + throw new Error("The first argument to the distinct command must be a string but was a " + + keyStringType); } if (query != null && queryType != "object") { - throw new Error("The query argument to the distinct command must be a document but was a " + queryType); + throw new Error("The query argument to the distinct command must be a document but was a " + + queryType); } // Distinct command var cmd = { - distinct : this.getName(), - key : keyString, - query : query || {} + distinct: this.getName(), + key: keyString, + query: query || {} }; // Set maxTimeMS if provided @@ -1654,8 +1762,8 @@ DBCollection.prototype.distinct = function(keyString, query, options){ return res.values; }; -DBCollection.prototype._distinct = function( keyString , query ){ - return this._dbReadCommand( { distinct : this._shortName , key : keyString , query : query || {} } ); +DBCollection.prototype._distinct = function(keyString, query) { + return this._dbReadCommand({distinct: this._shortName, key: keyString, query: query || {}}); }; /** @@ -1663,8 +1771,8 @@ DBCollection.prototype._distinct = function( keyString , query ){ * Holds a reference to the collection. * Proxy for planCache* commands. */ -if ( ( typeof PlanCache ) == "undefined" ){ - PlanCache = function( collection ){ +if ((typeof PlanCache) == "undefined") { + PlanCache = function(collection) { this._collection = collection; }; } @@ -1673,15 +1781,14 @@ if ( ( typeof PlanCache ) == "undefined" ){ * Name of PlanCache. * Same as collection. */ -PlanCache.prototype.getName = function(){ +PlanCache.prototype.getName = function() { return this._collection.getName(); }; - /** * toString prints the name of the collection */ -PlanCache.prototype.toString = function(){ +PlanCache.prototype.toString = function() { return "PlanCache for collection " + this.getName() + '. Type help() for more info.'; }; @@ -1690,7 +1797,7 @@ PlanCache.prototype.shellPrint = PlanCache.prototype.toString; /** * Displays help for a PlanCache object. */ -PlanCache.prototype.help = function () { +PlanCache.prototype.help = function() { var shortName = this.getName(); print("PlanCache help"); print("\tdb." + shortName + ".getPlanCache().help() - show PlanCache help"); |